System.IO.File クラスの静的メソッド、ReadAllText および ReadAllLines を使用して、テキスト ファイルの内容を読み込む例を次に示します。
注意
この例で使用されているファイルは、「方法: テキスト ファイルに書き込む (C# プログラミング ガイド)」のトピックで作成したものです。
使用例
class ReadFromFile
{
static void Main()
{
// The files used here were created in the code example
// in How to: Write to a Text File. You can of course substitute
// other files of your own.
// Example #1
// Read the file as one string.
string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
// Display the file contents to the console.
System.Console.WriteLine("Contents of writeText.txt = {0}", text);
// Example #2
// Read the file lines into a string array.
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");
System.Console.WriteLine("Contents of writeLines2.txt =:");
foreach (string line in lines)
{
Console.WriteLine("\t" + line);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
コードのコンパイル
コードをコピーし、コンソール アプリケーションに貼り付けます。
"c:\testdir" を実際のフォルダー名に置き換えます。
信頼性の高いプログラミング
次の条件を満たす場合は、例外が発生する可能性があります。
- ファイルが存在しない。
セキュリティ
ファイル名からファイルの内容を判断しないでください。 たとえば、myFile.cs ファイルが C# ソース ファイルとは限りません。