문제

가능한 중복:
기음#줄 단위로 파일 읽기
텍스트 리더에서 줄을 반복하는 방법?

나는 닷넷을 받았다 텍스트 리더 (순차적인 일련의 문자를 읽을 수 있는 클래스).어떻게 줄별로 콘텐츠를 반복 할 수 있습니까?

도움이 되었습니까?

해결책

이런 뜻인가요?

string line = null;
while((line = reader.ReadLine()) != null) 
{
    // do something with line
}

다른 팁

당신이 사용할 수 있도록 당신은 아주 쉽게 확장 방법을 만들 수 있습니다 foreach:

public static IEnumerable<string> ReadLines(this TextReader reader)
{
    string line = null;
    while((line = reader.ReadLine()) != null) 
    {
        yield return line;
    }
}

이 점에 유의하십시오. 하지 않을 것이다 끝에 당신을 위해 독자를 닫습니다.

그런 다음 다음을 사용할 수 있습니다:

foreach (string line in reader.ReadLines())

편집:의견에 언급 한 바와 같이,이 게으른입니다.모든 줄을 메모리로 읽는 대신 한 번에 한 줄만 읽습니다.

내가 지금 가지고있는 비 게으른 해결책:

foreach(string line in source.ReadToEnd().Split(Environment.NewLine.ToArray(),StringSplitOptions.None))

당신은 다음과 같이 그것을 사용할 것입니다:

string line;
while ((line = myTextReader.ReadLine()) != null)
{
    //do whatever with "line";
}

또는

string Myfile = @"C:\MyDocument.txt";
using(FileStream fs = new FileStream(Myfile, FileMode.Open, FileAccess.Read))
{                    
    using(StreamReader sr = new StreamReader(fs))
    {
        while(!sr.EndOfStream)
        {
            Console.WriteLine(sr.ReadLine());
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top