【问题标题】:How to modify this SearchAndReplace routine to work with large files如何修改此 SearchAndReplace 例程以处理大文件
【发布时间】:2012-07-26 05:29:16
【问题描述】:

我想修改以下代码以处理大文件。

    public static void Replace(string filePath, string searchText, string replaceText)
    {
        StreamReader reader = new StreamReader(filePath);
        string content = reader.ReadToEnd();
        reader.Close();

        content = Regex.Replace(content, searchText, replaceText);

        StreamWriter writer = new StreamWriter(filePath);
        writer.Write(content);
        writer.Close();
    }

我在想我需要打开一个文件流来写入一个新的文件名,然后删除原始文件并在完成后用新文件替换它。听起来对吗?

还有... 我喜欢这个例程的简单性,除了必要的文件 i/o 代码行之外,只有一行代码来处理文件。但是,我也想知道我是否会为了简单而牺牲性能...... Regex.Replace 是否非常高效?

【问题讨论】:

    标签: c# performance file-io large-files


    【解决方案1】:

    第一:你可以试试Regex with Stream(好像更快更省内存):

    或查看 Mono-Project Regex。它具有带流的正则表达式。

    请参阅这篇文章了解正则表达式的性能:

    或者如果没有必要使用Regex,请使用String.Replace并尝试这一行代码:

    File.WriteAllText(filePath, 
                      File.ReadAllText(filePath).Replace(searchText, replaceText));
    

    【讨论】:

    • ReadAllText 不是要把整个文件读入内存吗?这个问题的主要部分是关于修改它以处理大文件,因为我在尝试一次加载整个文件时遇到内存异常。
    • @BrandonMoore:我还建议Regex with Stream
    【解决方案2】:

    加快正则表达式的一种方法是传递 RegexOptions.Compiled 选项,该选项将使用您的正则表达式并将状态机编译到 IL。这对编译步骤有一些开销,但是一旦编译,正则表达式将执行得更快。显然,您应该对代码进行计时,看看 Regex 编译对您的场景有帮助还是有害。

    【讨论】:

      【解决方案3】:

      您也可以使用 File 类在不使用正则表达式的情况下做到这一点

      public static void Replace(string filePath, string searchText, string replaceText)
      {
         string newText = File.ReadAllText(filePath).Replace(searchText, replaceText));
         File.Delete(filePath);
         File.WriteAllText(newFilePath, newText);
      }
      

      【讨论】:

      • 您可能忽略了主要问题,即我需要它来处理大文件。 ReadToEnd 给了我一个内存异常,我猜 ReadAllText 也会这样做。
      • @BrandonMoore 试试这个,否则我会给你另一种解决方案,不会一次消耗所有大量内存
      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多