Your code did not change anything by one simple reason: the matching string wasn't found by Regex. If you actually see it in the file but it is not found may indicate that the file is binary. Not all content is a correct string in the encoding you use. Characters does not have one-to-one correspondence with bytes (it depends on encoding). So, you need to use binary approach, even when you replace a string. A binary file may contain a valid string in any encoding, but not every binary file contain a valid string. You can use instead:
http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx[
^].
Then, to be able to insert, you have to change the size of output array. So, the intermediate container should be resizeable. It could be
System.Collections.Generic.List<byte>
, and at the end, before writing, you can use its
ToArray()
method.
I assumed the file is not very big, as you already had the copy of it in memory. But, if the file is big, you also could use the classes
System.IO.BinaryReader
and
System.IO.BinaryWriter
:
http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.io.binarywriter.aspx[
^].
Insertion/replacement would require intermediate storage: you should break the file in three parts (before patter, the pattern itself, after pattern) and read them separately (in practice, it's enough to remember the indices of those fragments) and then write in three different parts, with middle part replaces.
You will have to write your own search algorithm though. So, wouldn't it be better to review your date storage format? Think about it. Unfortunately, you did not share your goals, so I cannot advise more on that.
—SA