Dacto
Dacto

Reputation: 2911

C# How to write one byte at an offset?

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?

Upvotes: 1

Views: 5659

Answers (3)

Jason Williams
Jason Williams

Reputation: 57892

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)

Upvotes: 2

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

You could cast to byte:

bw.Write((byte)0xB0);

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

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171744

change

bw.Write(0xB0);

to

bw.Write((byte)0xB0);

Upvotes: 3

Related Questions