【问题标题】:Replace one specific line in a huge text file替换大文本文件中的特定行
【发布时间】:2013-11-28 12:45:24
【问题描述】:

我想替换文本文件中的一个特定行。最简单的解决方案是:

public void ModifyFile(string path, int line, string targetText) {
    var lines = File.ReadAllLines(path);
    lines[line] = targetText;
    File.WriteAllLines(path, lines);
}

问题是,如果文件足够大,我会得到一个System.OutOfMemoryException,因为File.ReadAllLines() 会尝试将整个文件加载到内存中,而不是逐行加载。

我知道还有另一种方法可以以更少的内存成本读取特定行:

var line = File.ReadLines(path).Skip(line-1).Take(1).ToString();

如何替换文件中的那一行?

我正在寻找类似FileStream.Write Method:

var writer = File.OpenWrite(path);
writer.Write(Encoding.UTF8.GetBytes(targetText), 
    offset, Encoding.UTF8.GetByteCount(targetText));

但很难知道offset

有更好的方法吗?

-- 更新--

答案建议的临时文件解决方案效果很好。
同时,我想知道,如果我知道line 是一个小数字(line 让我们说)?如果我想更改具有 100m 行的文本文件中的第 10 行,必须有更好的解决方案。

【问题讨论】:

标签: c#


【解决方案1】:

您可以使用流一次读取文件一行,然后将内容复制到新文件中,或者使用备份名称重命名旧文件,然后进行处理;

string line;
int couinter = 0;

// Read the file and display it line by line.
System.IO.StreamReader reader = new System.IO.StreamReader(path);
System.IO.StreamWriter writer = new System.IO.StreamWriter(new_path);

while((text = reader.ReadLine()) != null)
{
   // Check for your content and replace if required here  
   if ( counter == line ) 
      text = targetText;

   writer.writeline(text);
   counter++;
}

reader.Close();
writer.Close();

【讨论】:

  • 如果我知道line 是一个小数字(比方说 1 亿),是否有特定的案例解决方案?
  • 这是我在回答中提到的精确算法的实现。 :)
【解决方案2】:

您可以做的是使用 StreamReader(它提供 ReadLine 方法)打开 FileStrem。现在逐行读取并将输出逐行写入临时文件。当您在所需的线路上时,只需更改线路。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2019-03-02
    • 2017-11-03
    • 2014-05-20
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多