방법: 파일에서 텍스트 읽기

다음 예제에서는 데스크톱 응용 프로그램용 .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 앱에서 비동기식 읽기

다음 예제에서는 WPF(Windows Presentation Foundation) 앱에서 비동기식 읽기 작업을 보여줍니다.

중요

이 예제에서는 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

참조