如何:从文件中读取文本How to: Read text from a file

下面的示例演示如何使用适用于桌面应用的 .NET 以异步方式和同步方式从文本文件中读取文本。The following examples show how to read text synchronously and asynchronously from a text file using .NET for desktop apps. 在这两个示例中,当你创建 StreamReader 类的实例时,你会提供文件的绝对路径或相对路径。In both examples, when you create the instance of the StreamReader class, you provide the relative or absolute path to the file.

备注

这些代码示例不适用于针对通用 Windows (UWP) 应用的开发,因为 Windows 运行时提供了对文件进行读写操作的不同的流类型。These code examples do not apply to developing for Universal Windows (UWP) apps, because the Windows Runtime provides different stream types for reading and writing to files. 有关演示如何在 UWP 应用中读取文本的示例,请参阅快速入门:对文件执行读取和写入操作For an example that shows how to read text from a file in a UWP app, see Quickstart: Reading and writing files. 有关演示如何在 .NET Framework 流和 Windows 运行时流之间进行转换的示例,请参阅如何:在 .NET Framework 流和 Windows 运行时流之间进行转换For examples that show how to convert between .NET Framework streams and Windows Runtime streams, see How to: Convert between .NET Framework streams and Windows Runtime streams.

示例:控制台应用中的同步读取Example: Synchronous read in a console app

以下示例演示控制台应用中的同步读取操作。The following example shows a synchronous read operation within a console app. 此示例使用流读取器打开文本文件,将内容复制到字符串并将字符串输出到控制台。This example opens the text file using a stream reader, copies the contents to a string, and outputs the string to the console.

重要

该示例假定名为 TestFile.txt 的文件已存在于与应用相同的文件夹中。The example assumes that a file named TestFile.txt already exists in the same folder as the app.

using System;
using System.IO;

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

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

示例:WPF 应用中的异步读取Example: Asynchronous read in a WPF app

以下示例演示 Windows Presentation Foundation (WPF) 应用中的异步读取操作。The following example shows an asynchronous read operation in a Windows Presentation Foundation (WPF) app.

重要

该示例假定名为 TestFile.txt 的文件已存在于与应用相同的文件夹中。The example assumes that a file named TestFile.txt already exists in the same folder as the app.

using System;
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 (StreamReader sr = new StreamReader("TestFile.txt"))
                {
                    string line = await sr.ReadToEndAsync();
                    ResultBlock.Text = line;
                }
            }
            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 StreamReader = New StreamReader("TestFile.txt")
                Dim line = Await sr.ReadToEndAsync()
                ResultBlock.Text = line
            End Using
        Catch ex As FileNotFoundException
            ResultBlock.Text = ex.Message
        End Try
    End Sub
End Class

请参阅See also