ファイルからのテキストの読み取り

次に、.NET デスクトップ アプリを使用してテキスト ファイルから同期でテキストを読み取る方法と非同期でテキストを読み取る方法の例を示します。 どちらの例でも、StreamReader クラスのインスタンスを作成する場合に、ファイルの相対パスまたは絶対パスを指定します。

Note

Windows ランタイムではファイルに対する読み取りと書き込みに別のストリーム型が用意されているため、これらのコード例はユニバーサル Windows プラットフォーム (UWP) アプリには適用されません。 詳細については、UWP ファイルを操作するに関するページを参照してください。 .NET Framework ストリームと Windows ランタイム ストリーム間で変換を行う方法を示す例については、「方法: .NET Framework ストリームと Windows ランタイム ストリームの間で変換を行う」を参照してください。

前提条件

  • アプリと同じフォルダーに TestFile.txt という名前のテキスト ファイルを作成します。

    テキスト ファイルに何らかのコンテンツを追加します。 この記事の例では、テキスト ファイルの内容をコンソールに書き込みます。

ファイルを読み取る

次の例では、コンソール アプリ内での同期読み取り操作を示します。 ファイルの内容が読み取られ、文字列変数に格納されてから、コンソールに書き込まれます。

  1. StreamReader インスタンスを作成します。
  2. StreamReader.ReadToEnd() メソッドを呼び出し、結果を文字列に割り当てます。
  3. コンソールに出力を書き込みます。
try
{
    // Open the text file using a stream reader.
    using StreamReader reader = new("TestFile.txt");

    // Read the stream as a string.
    string text = reader.ReadToEnd();

    // Write the text to the console.
    Console.WriteLine(text);
}
catch (IOException e)
{
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}
Try
    ' Open the text file using a stream reader.
    Using reader As New StreamReader("TestFile.txt")

        ' Read the stream as a string.
        Dim text As String = reader.ReadToEnd()

        ' Write the text to the console.
        Console.WriteLine(text)

    End Using
Catch ex As IOException
    Console.WriteLine("The file could not be read:")
    Console.WriteLine(ex.Message)
End Try

ファイルを非同期に読み取る

次の例では、コンソール アプリ内での非同期読み取り操作を示します。 ファイルの内容が読み取られ、文字列変数に格納されてから、コンソールに書き込まれます。

  1. StreamReader インスタンスを作成します。
  2. StreamReader.ReadToEndAsync() メソッドを待機し、結果を文字列に割り当てます。
  3. コンソールに出力を書き込みます。
try
{
    // Open the text file using a stream reader.
    using StreamReader reader = new("TestFile.txt");

    // Read the stream as a string.
    string text = await reader.ReadToEndAsync();

    // Write the text to the console.
    Console.WriteLine(text);
}
catch (IOException e)
{
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}
Try
    ' Open the text file using a stream reader.
    Using reader As New StreamReader("TestFile.txt")

        ' Read the stream as a string.
        Dim text As String = Await reader.ReadToEndAsync()

        ' Write the text to the console.
        Console.WriteLine(text)

    End Using
Catch ex As IOException
    Console.WriteLine("The file could not be read:")
    Console.WriteLine(ex.Message)
End Try