作法:讀取檔案中的文字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 執行階段提供不同的資料流類型來讀取和寫入檔案,因此這些程式碼不適用於 Universal Windows (UWP) 應用程式的開發工作。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