Reputation: 19
I need help to write hex data AB at adress 0x0156 in binary file in c#. What i used BinaryWriter gives wrong data 00.
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Write("AB");
bw.Dispose();
Upvotes: 0
Views: 1738
Reputation: 6773
If you need to write it at address 0x156 you need to move there first using the Seek method. You also need to write a byte value rather than a string.
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Seek(0x156,SeekOrigin.Begin);
bw.Write((byte)0xab);
bw.Dispose();
If the file does not exist, or is shorter than 343 bytes, it will be padded with 0 values up to the 342nd byte.
If you want to write a number of bytes starting from a particular location you could do something like this :
int StartLocation = 0x202;
int EndLocation = 0x30b;
byte ValueToWrite = 0xFF;
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Seek(StartLocation,SeekOrigin.Begin);
for (int CurLocation = StartLocation; CurLocation <= EndLocation; CurLocation++)
bw.Write(ValueToWrite);
bw.Dispose();
Another way would be
int StartLocation = 0x202;
int EndLocation = 0x30b;
byte ValueToWrite = 0xFF;
byte [] ByteArray = new byte[EndLocation-StartLocation+1];
for (int i = 0; i < ByteArray.Length; i++)
ByteArray[i] = ValueToWrite;
BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Seek(StartLocation,SeekOrigin.Begin);
bw.Write(ByteArray);
bw.Dispose();
Upvotes: 4