如何:從檔案讀取文字

下列範例將示範如何以同步和非同步方式,從使用適用於桌面應用程式的 .NET 之文字檔讀取文字。 在這兩個範例中,當您建立 StreamReader 類別的執行個體時,會提供檔案的相對路徑或絕對路徑。

注意

由於 Windows 執行階段提供不同的資料流類型來讀取和寫入檔案,因此這些程式碼不適用於 Universal Windows (UWP) 應用程式。 如需示範如何在 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

另請參閱