C# テキストファイルにデータを書き込む

C#で、StreamWriterを使用して、テキストファイルにデータを書き込むサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Microsoft Visual Studio Community 2019 Version 16.7.1
StreamWriter使い方
StreamWriterを使用すると、テキストファイルにデータを書き込むことが可能です。
StreamWriterstr = new StreamWriter("ファイル名");
以下は、「sample.txt」に「Hello World!」という文字列を書き込むサンプルコードとなります。
using System;
using System.IO;
using System.Text;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
StreamWriter str = new StreamWriter(
"sample.txt",
false);
str.WriteLine("Hello World!");
str.Close();
}
}
}
sample.txt

上書きではなくデータを追加する場合は、第2引数を「true」にします。
using System;
using System.IO;
using System.Text;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
StreamWriter str = new StreamWriter(
"sample.txt",
true);
str.WriteLine("Hello World!");
str.Close();
}
}
}
sample.txt

-
前の記事
Ubuntu コンソール上でパックマンを遊ぶ 2021.06.15
-
次の記事
javascript オブジェクトのプロパティをflatに取得する 2021.06.16
コメントを書く