方法: テキスト ファイルに書き込む (C# プログラミング ガイド)
テキストをファイルに書き込むさまざまな方法を次の例に示します。 最初の 2 つの例では、System.IO.File クラスの静的メソッドを使用して、文字列の完全な配列または完全な文字列をテキスト ファイルに書き込みます。 例 3 は、ファイルに書き込む前に各行を個別に処理する必要がある場合に、テキストをファイルに追加する方法を示します。 例 1 ~ 3 はすべて、ファイル内の既存の内容をすべて上書きします。 例 4 は、テキストを既存のファイルに追加する方法を示します。
使用例
class WriteTextFile
{
static void Main()
{
// These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
// You can modify the path if necessary.
// Example #1: Write an array of strings to a file.
// Create a string array that consists of three lines.
string[] lines = {"First line", "Second line", "Third line"};
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
// Example #2: Write one string to a text file.
string text = "A class is the most powerful data type in C#. Like structures, " +
"a class defines the data and behavior of the data type. ";
System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);
// Example #3: Write only some strings in an array to a file.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
{
foreach (string line in lines)
{
if (line.Contains("Second") == false)
{
file.WriteLine(line);
}
}
}
// Example #4: Append new text to an existing file
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
{
file.WriteLine("Fourth line");
}
}
}
/* Output (to WriteLines.txt):
First line
Second line
Third line
Output (to WriteText.txt):
A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type.
Output to WriteLines2.txt after Example #3:
First line
Third line
Output to WriteLines2.txt after Example #4:
First line
Third line
Fourth line
*/
コードのコンパイル
コードをコンソール アプリケーションにコピーします。
"c:\testdir" をコンピューター上の実際のフォルダー名に置き換えるか、またはその名前でフォルダーを作成します。
信頼性の高いプログラミング
次の条件を満たす場合は、例外が発生する可能性があります。
ファイルは存在するが、読み取り専用である。
パス名が長すぎる。
ディスクがいっぱいになっている。