使用 crlf 行定界符读取大文本文件的最佳方法
Best way to read BIG text files with crlf line delimiter
我有一个非常大的逗号分隔文本文件。如前所述,每个字段都用逗号分隔并用引号括起来(所有字符串)。问题是某些字段包含该字段中多行的 CR。因此,当我执行 ReadLine 时,它会在该 CR 处停止。如果我可以告诉它只在 CRLF 组合处停止,那就太好了。
有没有人有任何快速的方法来做到这一点?文件可以非常非常大。
使用怎么样
string line = File.ReadAllText("input.txt"); // Read the text in one line
然后将其拆分到托架 return/line 进纸中,如下所示:
var split = line.Split('\n'); // I'm not really sure it's \n you'll need, but it's something!
然后循环处理
foreach(var line in split) { ... }
如果你想要具体的ReadLine
,为什么不实施呢?
public static class MyFileReader {
public static IEnumerable<String> ReadLineCRLF(String path) {
StringBuilder sb = new StringBuilder();
Char prior = '[=10=]';
Char current = '[=10=]';
using (StreamReader reader = new StreamReader(path)) {
int v = reader.Read();
if (v < 0) {
if (prior == '\r')
sb.Append(prior);
yield return sb.ToString();
yield break;
}
prior = current;
current = (Char) v;
if ((current == '\n') && (prior == '\r')) {
yield return sb.ToString();
sb.Clear();
}
else if (current == '\r') {
if (prior == '\r')
sb.Append(prior);
}
else
sb.Append(current);
}
}
}
那就用吧
var lines = MyFileReader
.ReadLineCRLF(@"C:\MyData.txt");
我有一个非常大的逗号分隔文本文件。如前所述,每个字段都用逗号分隔并用引号括起来(所有字符串)。问题是某些字段包含该字段中多行的 CR。因此,当我执行 ReadLine 时,它会在该 CR 处停止。如果我可以告诉它只在 CRLF 组合处停止,那就太好了。
有没有人有任何快速的方法来做到这一点?文件可以非常非常大。
使用怎么样
string line = File.ReadAllText("input.txt"); // Read the text in one line
然后将其拆分到托架 return/line 进纸中,如下所示:
var split = line.Split('\n'); // I'm not really sure it's \n you'll need, but it's something!
然后循环处理
foreach(var line in split) { ... }
如果你想要具体的ReadLine
,为什么不实施呢?
public static class MyFileReader {
public static IEnumerable<String> ReadLineCRLF(String path) {
StringBuilder sb = new StringBuilder();
Char prior = '[=10=]';
Char current = '[=10=]';
using (StreamReader reader = new StreamReader(path)) {
int v = reader.Read();
if (v < 0) {
if (prior == '\r')
sb.Append(prior);
yield return sb.ToString();
yield break;
}
prior = current;
current = (Char) v;
if ((current == '\n') && (prior == '\r')) {
yield return sb.ToString();
sb.Clear();
}
else if (current == '\r') {
if (prior == '\r')
sb.Append(prior);
}
else
sb.Append(current);
}
}
}
那就用吧
var lines = MyFileReader
.ReadLineCRLF(@"C:\MyData.txt");