我有一个4GB的文件,想要进行基于字节的查找和替换。我写了一个简单的程序来实现它,但是执行一个查找和替换需要太长时间(超过90分钟),而一些我尝试过的十六进制编辑器可以在不将整个目标文件加载到内存中的情况下在3分钟以内完成任务。是否有人知道我可以实现相同功能的方法?以下是我的当前代码:
public int ReplaceBytes(string File, byte[] Find, byte[] Replace)
{
var Stream = new FileStream(File, FileMode.Open, FileAccess.ReadWrite);
int FindPoint = 0;
int Results = 0;
for (long i = 0; i < Stream.Length; i++)
{
if (Find[FindPoint] == Stream.ReadByte())
{
FindPoint++;
if (FindPoint > Find.Length - 1)
{
Results++;
FindPoint = 0;
Stream.Seek(-Find.Length, SeekOrigin.Current);
Stream.Write(Replace, 0, Replace.Length);
}
}
else
{
FindPoint = 0;
}
}
Stream.Close();
return Results;
}
顺便说一下,“查找和替换”与那个4GB的“文件”相比较小。我很容易看出我的算法为什么慢,但我不确定如何改进。