gpt4 book ai didi

c# - 替换一个巨大的文本文件中的特定行

转载 作者:行者123 更新时间:2023-12-03 19:00:54 25 4
gpt4 key购买 nike

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

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 < 100 让我们说)?如果我想更改具有 100m 行的文本文件中的第 10 行,必须有更好的解决方案。

最佳答案

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

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

关于c# - 替换一个巨大的文本文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20234071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com