2012-10-02 52 views
0

可能重複:
C# Reading a File Line By Line
How to loop over lines from a TextReader?如何遍歷TextReader的每一行?

我給一個.NET TextReader(可讀取連續字符系列的一類)。我如何循環播放其內容?

+0

注意,給予'TextReader'你不能確定你真正閱讀「的所有」行。如果有人在向你傳遞引用之前調用了任何'Read *()'方法,你就不會知道。 YMMV是否是一個問題。 –

+3

我的答案與[上次提問時相同](http://stackoverflow.com/questions/12687453/how-to-loop-over-lines-from-a-textreader/12687525#12687525) – Rawling

+1

我想知道爲什麼它很難在文檔中找到它:['TextReader.ReadLine'方法](http://msdn.microsoft.com/en-us/library/system.io.textreader.readline.aspx) –

回答

3

你的意思是這樣的嗎?

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

你會使用這樣的:

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

OR

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()); 
     } 
    } 
} 
2

你可以非常容易地創建一個擴展方法,這樣就可以使用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()) 

編輯:正如在評論中指出,這是懶惰的。它只會一次讀取一行,而不是將所有行讀入內存。

+0

是這個*懶惰*枚舉? –

+0

你不是指'收益率回報率'嗎?這是從另一個口令複製的嗎? 8-o – Rawling

+0

@Rawling:是的,我確實是這個意思。是的,我複製鍋爐位:) –

0

的非懶解決方案,我目前所面對的:

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

你爲什麼不把它放在原來的問題中? – Tudor