【问题标题】:Best way to read BIG text files with crlf line delimiter使用 crlf 行分隔符读取 BIG 文本文件的最佳方式
【发布时间】:2016-05-10 12:56:52
【问题描述】:

我有一个非常大的逗号分隔文本文件。如前所述,每个字段由逗号分隔并由引号(所有字符串)包围。问题是某些字段包含该字段中多行的 CR。因此,当我执行 ReadLine 时,它​​会停在该 CR 处。如果我能告诉它只停在 CRLF 组合上,那就太好了。

有没有人有任何快速的方法来做到这一点?文件可能非常非常大。

【问题讨论】:

  • 查看MSDN post
  • 请提供您的代码 (sn-p)!根据我的经验,使用 Microsoft.VisualBasic.FileIO.TextFieldParser 对我有很大帮助!
  • “非常非常大”有多大?我们是在谈论 10 兆字节、100 兆字节、100 兆字节吗?对预期大小的一些想法,或者更好的是,最大大小会有所帮助。

标签: c# asp.net regex readline


【解决方案1】:

如果你想要特定的ReadLine,为什么不实现呢?

  public static class MyFileReader {
    public static IEnumerable<String> ReadLineCRLF(String path) {
      StringBuilder sb = new StringBuilder();

      Char prior = '\0';
      Char current = '\0';

      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"); 

【讨论】:

    【解决方案2】:

    如何使用

    string line = File.ReadAllText("input.txt"); // Read the text in one 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) { ... }
    

    【讨论】:

    • 我试过这个:Regex splitter = new Regex("\r\n"); string[] AllLines = splitter.Split(iFile.ReadToEnd());有点你所指的,但在 CRLF 上分裂,但我仍然偶尔会在 CR 上分裂。很奇怪。
    猜你喜欢
    • 2011-12-06
    • 2010-10-07
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多