逐块读取文本文件
我正在使用 C#.net
如何逐块读取文本文件,块由换行符分隔。
块大小不固定,因此我无法使用 StreamReader 的 ReadBlock 方法。
是否有其他方法可以逐块获取数据,因为数据由换行符分隔。
I am using C#.net
How can read a text file block by block, the block is separated by new line character.
Block size is not fixed, so i am not able to use ReadBlock method of StreamReader.
Is there any ohter method for getting the data block by block as it is separated by new line character.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 StreamReader:
此方法读取文本逐行文件(其中Environment.NewLine用作行分隔符)并且一次仅将当前行加载到内存中,因此它可用于读取非常大的文件。
如果您只想将小文本文件的所有行加载到内存中,您也可以使用 ReadAllLines 方法:
You could use a StreamReader:
This method reads the text file line by line (where Environment.NewLine is used as line separator) and has only the current line loaded in memory at once so it could be used to read very large files.
If you just want to load all the lines of a small text file in memory you could also use the ReadAllLines method:
您可以查看 StreamReader.ReadToEnd() 和 String.Split()
的使用:
You can look at
StreamReader.ReadToEnd()
andString.Split()
use:
您可以使用 File.ReadLines 方法
ReadLines
返回一个IEnumerable
,因此一次只有一行存储在内存中。You could use the File.ReadLines method
ReadLines
returns anIEnumerable<string>
so only one line is stored in memory at once.类似这样的事情:
有趣的是,前几天我正在做一些文件 i/o,发现 this 这非常有用处理大型分隔记录文本文件(例如,将记录转换为您自己定义的预定义类型)
Something like:
Funny I was doing some file i/o the other day, and found this which was very useful at processing large delimited record text files (e.g. converting a record to a pre-defined type which you define yourself)