I have a 4Gb file in which I want to search and replace bytes. I wrote a simple program, but it takes too much time (90 minutes +) to do just one search and a replacement. Several hex editors that I tried can complete the task in less than 3 minutes and not load the entire target file into memory. Does anyone know a method where I can do the same thing? Here is my current code:
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; }
Find and replace relatively small compared to the 4Gb file. I can easily understand why my algorithm is slow, but I'm not sure how I could do it better.
cgimusic
source share