2012-01-18 63 views
0

我使用C#.NET閱讀文本文件,逐塊

如何可以讀取塊的文本文件塊,塊是由新行字符分隔。

塊大小不固定,所以我無法使用StreamReader的ReadBlock方法。

有沒有其他方法可以逐塊獲取數據塊,因爲它是由換行符分隔的。

+0

你試過了什麼代碼? – annonymously

+3

使用StreamReader.ReadLine()方法。 – adatapost

回答

3

你可以使用一個StreamReader

using (var reader = File.OpenText("foo.txt")) 
{ 
    string line; 
    while ((line = reader.ReadLine()) != null) 
    { 
     // do something with the line 
    } 
} 

這種方法逐行讀取(其中Environment.NewLine用作行分隔符)的文本文件,行,只加載到內存中當前行一次,因此可以用來讀取非常大的文件。

如果你只是想要加載在內存中的小文本文件的所有行,你也可以使用ReadAllLines方法:

string[] lines = File.ReadAllLines("foo.txt"); 
// the lines array will contain all the lines 
// don't use this method with large files 
// as it loads the entire contents into memory 
0

喜歡的東西:

using (TextReader tr = new StreamReader(FullFilePath)) 
{ 
    string Line; 
    while ((Line = tr.ReadLine()) != null) 
    { 
    Line = Line.Trim(); 
    } 
} 

有趣,我在做一些文件I/O,並發現this這是非常有用的處理大分隔記錄文本文件(例如轉換爲您自己定義的預定義類型的記錄)

0

你可以看一下StreamReader.ReadToEnd()String.Split()

使用:

string content = stream.ReadToEnd(); 
string[] blocks = content.Split('\n');//You may want to use "\r\n" 
+1

爲什麼要經歷所有這些痛苦時,有一種方法可以讓你做到這一點? –

+0

哦,你的權利。之前我沒有注意到。那麼,沒用的答案。雖然,我的方法可以將文件分割成由任何分隔符分隔的塊。 – annonymously

0

你可以使用File.ReadLines方法

foreach(string line in File.ReadLines(path)) 
{ 
    //do something with line 
} 

ReadLines返回IEnumerable<string>所以只有一個行存儲在內存中一次。