blah blah blah is here! blah blah » Close

up2down
link

if I have a existing binary file of 20 bytes, and I want to replace (over-write) portion of that file, say 4 bytes, from index 10 to index 13, how could I do that?

I understand that FileMode.Append could be used, but it always append at the end, with offset 0.

I would appreciate if some code samples are shown.

thanks.

foamy
2499

You will probably need to read the file into memory, alter it and write the entire thing back

last answered 2 years ago

1 answers

link

I'd use a BinaryWriter for this and call the Seek() method on the underlying stream to move to the 11th byte in the file. Here's some code:

using System;
using System.IO;
using System.Text;

class Test
{
static void Main()
{
string fileName = "myfile.bin"; // or whatever
Encoding enc = Encoding.ASCII;

using(BinaryWriter bw = new BinaryWriter(File.Open(fileName, FileMode.Create), enc))
{
// write 20 bytes to file
bw.Write(enc.GetBytes("abcdefghijklmnopqrst"));
}

using(BinaryWriter bw = new BinaryWriter(File.Open(fileName, FileMode.Open), enc))
{
// overwrite 4 bytes from 10 to 13
bw.BaseStream.Seek(10, SeekOrigin.Begin);
bw.Write(enc.GetBytes("KLMN"));
}
}
}

thanks, that is a neat solution. I find similar solution at http://www.neowin.net/forum/index.php?showtopic=609069

Feedback