使用streamreader读取文本文件.
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string line = sr.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
我想迫使该行分隔符应该是\n没有\r.那我该怎么做呢?
我有一个大文件> 200MB.该文件是来自外部方的CSV文件,但遗憾的是我不能一行一行地读取文件,就像\r\n用于定义新行一样.
目前我正在阅读使用这种方法的所有行:
var file = File.ReadAllText(filePath, Encoding.Default);
var lines = Regex.Split(file, @"\r\n");
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
...
}
Run Code Online (Sandbox Code Playgroud)
我该如何优化呢?在我的225MB文件上调用ReadAllText后,该过程使用的RAM超过1GB.在我的情况下是否可以使用流式处理方法,我需要使用我的\r\n模式拆分文件?
编辑1:
使用File.ReadLines和StreamReader的解决方案将无法正常工作,因为它将文件中的每一行视为一行.我需要使用我的\r\n模式拆分文件.使用我的代码读取文件会产生758.371行(这是正确的),而正常的行计数结果超过150万行.
解
public static IEnumerable<string> ReadLines(string path)
{
const string delim = "\r\n";
using (StreamReader sr = new StreamReader(path))
{
StringBuilder sb = new StringBuilder();
while (!sr.EndOfStream)
{
for (int i = 0; i < delim.Length; i++)
{
Char …Run Code Online (Sandbox Code Playgroud)