关于二进制文件读写问题(BinaryWriter)

ybzsu 2009-12-10 07:57:03
二进制文件读写发现奇怪问题
FileStream fs = new FileStream(path, System.IO.FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write("11111");
写完后用UE打开发现第一个字节是0x05,后面的正常,在写其他东西发现都一样,第一个字节是写入的长度,请问大侠谁知道怎么回事啊?

还有,有没好的办法写入VC++ 6.0里面的结构体?
比如我定义的
char name[20]
char desc[100]
其实name一般也就10个byte以内,但是协议定的就20个字节,如果用bw还要计算实际的长度,然后补0进去,好麻烦
...全文
335 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
ybzsu 2009-12-11
  • 打赏
  • 举报
回复
感谢几位大哥,问题解决
用[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]写结构体,然后
序列化
public static byte[] rawSerialize(object obj)
{
int rawsize = Marshal.SizeOf(obj);
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.StructureToPtr(obj, buffer, false);
byte[] rawdatas = new byte[rawsize];
Marshal.Copy(buffer, rawdatas, 0, rawsize);
Marshal.FreeHGlobal(buffer);
return rawdatas;
}
最后System.IO.FileStream.Write写
宝_爸 2009-12-11
  • 打赏
  • 举报
回复
我在4楼说错了,写入长度不是应为类型。
而是
public virtual void Write(
string value
)
string类型的overload是特殊的

参考msdn
A length-prefixed string represents the string length by prefixing to the string a single byte or word that contains the length of that string. This method first writes the length of the string as a four-byte unsigned integer, and then writes that many characters to the stream. This method writes a length-prefixed string to this stream using the BinaryWriter instance's current Encoding
lld8925 2009-12-10
  • 打赏
  • 举报
回复
或者FileStream.Write

public override void Write(
byte[] array,
int offset,
int count
)
lld8925 2009-12-10
  • 打赏
  • 举报
回复
或者FileStream.Write

public override void Write(
byte[] array,
int offset,
int count
)
ybzsu 2009-12-10
  • 打赏
  • 举报
回复
太感谢楼上大侠了
想再请问下C++中

struct
{
char Num[20];
char Code[64];
int index;
}
这个结构体写入文件,C#该怎么写啊?
宝_爸 2009-12-10
  • 打赏
  • 举报
回复
BinaryWriter.Write用于写入有类型的数据

Write(Boolean)
Write(Byte)
Write(Double) 等,
因此需要写入长度
宝_爸 2009-12-10
  • 打赏
  • 举报
回复
或者FileStream.Write

public override void Write(
byte[] array,
int offset,
int count
)
宝_爸 2009-12-10
  • 打赏
  • 举报
回复
使用File.WriteAllBytes

public static void WriteAllBytes(
string path,
byte[] bytes
)
ybzsu 2009-12-10
  • 打赏
  • 举报
回复
奇怪奇怪,为什么多出一个字节?,第一个字节哪来的?!似乎是和写入的长度相同
写入空字符第一位就是0x00,写入2个字符,第一位就是0x02
见鬼了。。。

111,094

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧