[英]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. 问题在于BinaryWriter.Write(args)在该位置写入一个四字节有符号整数。 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?
然后稍后可能是另外两个字节,我该如何指定要写入多少个字节?
change 更改
bw.Write(0xB0);
to 至
bw.Write((byte)0xB0);
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: 绝对没有必要仅使用高级BinaryWriter向流中写入一个简单的字节-这样做更高效,更整洁:
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) (通常,在将BinaryWriter附加到流之后,您也不应该真正寻求-BinaryWriter应该控制流,并且更改“其背后”的内容有点脏)
You could cast to byte: 您可以转换为字节:
bw.Write((byte)0xB0);
This should cause the correct overloaded version of Write to be invoked. 这将导致调用正确的Write重载版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.