Share via


从文件读取文本

下面的示例演示如何使用适用于桌面应用的 .NET 以异步方式和同步方式从文本文件中读取文本。 在这两个示例中,当你创建 StreamReader 类的实例时,你会提供文件的绝对路径或相对路径。

注意

这些代码示例不适用于通用 Windows (UWP) 应用,因为 Windows 运行时提供了对文件进行读写操作的不同流类型。 有关详细信息,请参阅 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