StreamReader.ReadLine 메서드

정의

현재 스트림에서 문자 줄을 읽고 데이터를 문자열로 반환합니다.

public:
 override System::String ^ ReadLine();
public override string ReadLine();
public override string? ReadLine();
override this.ReadLine : unit -> string
Public Overrides Function ReadLine () As String

반품

입력 스트림의 다음 줄 또는 null 입력 스트림의 끝에 도달한 경우

예외

반환된 문자열에 버퍼를 할당할 메모리가 부족합니다.

I/O 오류가 발생합니다.

예제

다음 코드 예제에서는 파일의 끝에 도달할 때까지 파일에서 줄을 읽습니다.

using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    Console.WriteLine(sr.ReadLine());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Imports System.IO
Imports System.Text

Public Class Test

    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"

        Try
            If File.Exists(path) Then
                File.Delete(path)
            End If

            Dim sw As StreamWriter = New StreamWriter(path)
            sw.WriteLine("This")
            sw.WriteLine("is some text")
            sw.WriteLine("to test")
            sw.WriteLine("Reading")
            sw.Close()

            Dim sr As StreamReader = New StreamReader(path)

            Do While sr.Peek() >= 0
                Console.WriteLine(sr.ReadLine())
            Loop
            sr.Close()
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

설명

줄은 줄 바꿈("\n"), 캐리지 리턴("\r") 또는 줄 바꿈("\r\n")이 바로 뒤에 오는 캐리지 리턴 뒤에 오는 문자 시퀀스로 정의됩니다. 반환되는 문자열에는 종료 캐리지 리턴 또는 줄 바꿈이 포함되지 않습니다. 반환된 값은 null 입력 스트림의 끝에 도달하는 경우입니다.

스트림이 줄 바꿈 시퀀스로 끝나는 경우 빈 줄이 추가로 반환되지 않습니다. 예를 들어 포함하는 "line1\nline2\n" 스트림은 포함하는 스트림과 동일한 두 줄("line1""line2")을 생성합니다 "line1\nline2".

이 메서드는 TextReader.ReadLine를 재정의합니다.

현재 메서드가 throw OutOfMemoryException되는 경우 기본 개체의 판독기 Stream 위치는 메서드가 읽을 수 있는 문자 수만큼 고급이지만 내부 ReadLine 버퍼에 이미 읽은 문자는 삭제됩니다. 버퍼로 데이터를 읽은 후 기본 스트림의 위치를 조작하는 경우 내부 스트림의 위치가 내부 버퍼의 위치와 일치하지 않을 수 있습니다. 내부 버퍼를 다시 설정하려면 메서드를 DiscardBufferedData 호출합니다. 그러나 이 메서드는 성능을 저하시키며 반드시 필요한 경우에만 호출해야 합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

적용 대상

추가 정보