How to find the offsets of a string in file

  • Thread starter Thread starter Alex49_
  • Start date Start date
A

Alex49_

Guest
Hi guys,

I'm trying to search a large text file for a certain string and then ultimately replace that string with one of the same length, without making a whole new file. In order for me to write to the file in the most efficient way due to its size, I need some way of finding the offsets for every instance of a string within the file.

I saw a piece of code on this forum which finds the first occurrence, but because of my limitation in c# knowledge, I don't know how I could adapt this to find every occurrence.

This is the code:

public static string FindBytes(string fileName, byte[] bytes)
{
long i, j;
using (FileStream fs = File.OpenRead(fileName))
{
for (i = 0; i < fs.Length - bytes.Length; i++)
{
fs.Seek(i, SeekOrigin.Begin);
for (j = 0; j < bytes.Length; j++)
if (fs.ReadByte() != bytes[j]) break;
if (j == bytes.Length) break;
}
}
return i;
}

Any help would be appreciated. Thanks

Continue reading...
 
Back
Top