逐块读取文本文件
本文关键字:文件 取文本 读取 | 更新日期: 2023-09-27 18:20:34
我正在使用C#.net
如何逐块读取文本文件,块之间用换行符分隔。
块大小不是固定的,所以我不能使用StreamReader的ReadBlock方法。
有没有其他方法可以逐块获取数据,因为数据是由换行符分隔的。
您可以使用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
您可以查看StreamReader.ReadToEnd()
和String.Split()
用途:
string content = stream.ReadToEnd();
string[] blocks = content.Split(''n');//You may want to use "'r'n"
您可以使用File.ReadLines方法
foreach(string line in File.ReadLines(path))
{
//do something with line
}
CCD_ 3返回一个CCD_。
类似于:
using (TextReader tr = new StreamReader(FullFilePath))
{
string Line;
while ((Line = tr.ReadLine()) != null)
{
Line = Line.Trim();
}
}
有趣的是,前几天我做了一些文件I/o,发现这在处理大型分隔记录文本文件时非常有用(例如,将记录转换为您自己定义的预定义类型)