다음을 통해 공유


파일의 텍스트 읽기

다음 예제에서는 데스크톱 응용 프로그램용 .NET을 사용하여 텍스트 파일에서 텍스트를 동기 또는 비동기적으로 읽는 방법을 보여줍니다. 두 예제에서는 StreamReader 클래스의 인스턴스를 만들 때 파일의 상대 또는 절대 경로를 제공합니다.

참고

Windows 런타임에서는 파일을 읽고 파일에 쓰는 다양한 스트림 형식을 제공하기 때문에 관련 코드 예제는 UWP(유니버설 Windows 플랫폼) 앱에는 적용되지 않습니다. 자세한 내용은 UWP 파일 작업을 참조하세요. .NET Framework 스트림과 Windows 런타임 스트림 간의 변환 방법을 보여주는 예제는 방법: .NET Framework 스트림과 Windows 런타임 스트림 간 변환을 참조하세요.

필수 조건

  • 앱과 동일한 폴더에 TestFile.txt라는 텍스트 파일을 만듭니다.

    텍스트 파일에 일부 콘텐츠를 추가합니다. 이 문서의 예에서는 텍스트 파일의 콘텐츠를 콘솔에 씁니다.

파일 읽기

다음 예제에서는 콘솔 앱 내에서 동기식 읽기 작업을 보여줍니다. 파일 콘텐츠를 읽고 문자열 변수에 저장한 다음 콘솔에 씁니다.

  1. StreamReader 인스턴스를 만듭니다.
  2. StreamReader.ReadToEnd() 메서드를 호출하고 결과를 문자열에 할당합니다.
  3. 콘솔에 출력을 씁니다.
try
{
    // Open the text file using a stream reader.
    using StreamReader reader = new("TestFile.txt");

    // Read the stream as a string.
    string text = reader.ReadToEnd();

    // Write the text to the console.
    Console.WriteLine(text);
}
catch (IOException e)
{
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}
Try
    ' Open the text file using a stream reader.
    Using reader As New StreamReader("TestFile.txt")

        ' Read the stream as a string.
        Dim text As String = reader.ReadToEnd()

        ' Write the text to the console.
        Console.WriteLine(text)

    End Using
Catch ex As IOException
    Console.WriteLine("The file could not be read:")
    Console.WriteLine(ex.Message)
End Try

비동기적으로 파일 읽기

다음 예에서는 콘솔 앱 내의 비동기 읽기 작업을 보여 줍니다. 파일 콘텐츠를 읽고 문자열 변수에 저장한 다음 콘솔에 씁니다.

  1. StreamReader 인스턴스를 만듭니다.
  2. StreamReader.ReadToEndAsync() 메서드를 기다리고 결과를 문자열에 할당합니다.
  3. 콘솔에 출력을 씁니다.
try
{
    // Open the text file using a stream reader.
    using StreamReader reader = new("TestFile.txt");

    // Read the stream as a string.
    string text = await reader.ReadToEndAsync();

    // Write the text to the console.
    Console.WriteLine(text);
}
catch (IOException e)
{
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}
Try
    ' Open the text file using a stream reader.
    Using reader As New StreamReader("TestFile.txt")

        ' Read the stream as a string.
        Dim text As String = Await reader.ReadToEndAsync()

        ' Write the text to the console.
        Console.WriteLine(text)

    End Using
Catch ex As IOException
    Console.WriteLine("The file could not be read:")
    Console.WriteLine(ex.Message)
End Try