tags:

views:

529

answers:

3

Im trying to write a single byte at a certain location in a file. This is what im using at the moment:

BinaryWriter bw = new BinaryWriter(File.Open(filename, FileMode.Open));
bw.BaseStream.Seek(0x6354C, SeekOrigin.Begin);
bw.Write(0xB0);
bw.Close();

The problem is that BinaryWriter.Write(args) writes a four-byte signed integer at the position. I wish to only write one byte at the particular location. And then later possibly two bytes else where, how I specify how many bytes to write?

+2  A: 

change

bw.Write(0xB0);

to

bw.Write((byte)0xB0);
Philippe Leybaert
Thank you! so simple!!
Dacto
+1  A: 

You could cast to byte:

bw.Write((byte)0xB0);

This should cause the correct overloaded version of Write to be invoked.

Daniel Earwicker
+1  A: 

There is absolutely no need to use a high-level BinaryWriter just to write a simple byte to a stream - It's more efficient and tidy just to do this:

Stream outStream = File.Open(filename, FileMode.Open);
outStream.Seek(0x6354C, SeekOrigin.Begin);
outStream.WriteByte(0xb0);

(In general you also shouldn't really Seek after attaching a BinaryWriter to your stream - the BinaryWriter should be in control of the stream, and changing things "behind its back" is a bit dirty)

Jason Williams
Hmmm yes, higher level isnt nessecary, thanks.
Dacto