【发布时间】:2013-07-25 17:08:23
【问题描述】:
我现在正在研究一个允许编辑非常大的文本文件 (4Gb+) 的课程。好吧,这听起来可能有点愚蠢,但我不明白如何修改流中的文本。 这是我的代码:
public long Replace(String text1, String text2)
{
long replaceCount = 0;
currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
using (BufferedStream bs = new BufferedStream(currentFileStream))
using (StreamReader sr = new StreamReader(bs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(text1))
{
line.Replace(text1, text2);
// Here I should save changed line
replaceCount++;
}
}
}
return replaceCount;
}
【问题讨论】:
-
抱歉将您的样本(根本不写任何东西)与 Ehsan Ullah 的样本(使用
StringBuilder显然不会帮助您处理大文件)混为一谈。删除我的答案。 -
这在一般情况下是行不通的。只有在非常不寻常的情况下,更换的时间与原来的长度完全一样。文件不允许在文件中间插入和删除。因此需要完全重写文件。如果你有 4 个 jiggabyte 文本文件,那么你做错了。
-
@HansPassant,4GB+ 的文件不是操作的结果,但我正在处理现有的大文件...
标签: c# filestream streamreader streamwriter