如何:从文件中读取文本

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

注意

这些代码示例不适用于通用 Windows (UWP) 应用,因为 Windows 运行时提供了对文件进行读写操作的不同流类型。 有关演示如何在 UWP 应用中读取文本的示例,请参阅快速入门:对文件执行读取和写入操作。 有关演示如何在 .NET Framework 流和 Windows 运行时流之间进行转换的示例,请参阅如何:在 .NET Framework 流和 Windows 运行时流之间进行转换

示例:控制台应用中的同步读取

以下示例演示控制台应用中的同步读取操作。 此示例使用流读取器打开文本文件,将内容复制到字符串并将字符串输出到控制台。

重要

该示例假定名为 TestFile.txt 的文件已存在于与应用相同的文件夹中。

using System;
using System.IO;

class Program
{
    public static void Main()
    {
        try
        {
            // Open the text file using a stream reader.
            using (var sr = new StreamReader("TestFile.txt"))
            {
                // Read the stream as a string, and write the string to the console.
                Console.WriteLine(sr.ReadToEnd());
            }
        }
        catch (IOException e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}
Imports System.IO

Module Program
    Public Sub Main()
        Try
            ' Open the file using a stream reader.
            Using sr As New StreamReader("TestFile.txt")
                ' Read the stream as a string and write the string to the console.
                Console.WriteLine(sr.ReadToEnd())
            End Using
        Catch e As IOException
            Console.WriteLine("The file could not be read:")
            Console.WriteLine(e.Message)
        End Try
    End Sub
End Module

示例:WPF 应用中的异步读取

以下示例演示 Windows Presentation Foundation (WPF) 应用中的异步读取操作。

重要

该示例假定名为 TestFile.txt 的文件已存在于与应用相同的文件夹中。

using System.IO;
using System.Windows;

namespace TextFiles;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow() => InitializeComponent();

    private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            using (var sr = new StreamReader("TestFile.txt"))
            {
                ResultBlock.Text = await sr.ReadToEndAsync();
            }
        }
        catch (FileNotFoundException ex)
        {
            ResultBlock.Text = ex.Message;
        }
    }
}
Imports System.IO
Imports System.Windows

''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>

Partial Public Class MainWindow
    Inherits Window
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Async Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs)
        Try
            Using sr As New StreamReader("TestFile.txt")
                ResultBlock.Text = Await sr.ReadToEndAsync()
            End Using
        Catch ex As FileNotFoundException
            ResultBlock.Text = ex.Message
        End Try
    End Sub
End Class

请参阅