将十六进制数据写入特定地址c#的文件

时间:2018-01-09 17:08:14

标签: c# binary hex

我需要帮助在c#中的二进制文件中的地址0x0156处写入十六进制数据AB。 我使用的BinaryWriter提供了错误的数据00。

BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Write("AB");
bw.Dispose();

1 个答案:

答案 0 :(得分:2)

如果你需要在地址0x156写它,你需要先使用Seek方法移动它。您还需要编写字节值而不是字符串。

BinaryWriter bw = new BinaryWriter(File.OpenWrite(path));
bw.Seek(0x156,SeekOrigin.Begin);
bw.Write((byte)0xab);
bw.Dispose();

如果文件不存在,或者短于343个字节,则将使用0值填充,直到第342个字节。

如果你想从特定位置开始写一些字节,你可以这样做:

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();

另一种方式是

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();