二进制文件读写发现奇怪问题
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进去,好麻烦

解决方案 »

  1.   

    使用File.WriteAllBytes public static void WriteAllBytes(
    string path,
    byte[] bytes
    )
      

  2.   

    或者FileStream.Write public override void Write(
    byte[] array,
    int offset,
    int count
    )
      

  3.   

    BinaryWriter.Write用于写入有类型的数据

    Write(Boolean) 
    Write(Byte) 
    Write(Double) 等,
    因此需要写入长度 
      

  4.   

    太感谢楼上大侠了
    想再请问下C++中struct
    {
       char Num[20];
       char Code[64];
       int index;
    }
    这个结构体写入文件,C#该怎么写啊?
      

  5.   

    或者FileStream.Write public override void Write( 
    byte[] array, 
    int offset, 
    int count 
      

  6.   

    或者FileStream.Write public override void Write( 
    byte[] array, 
    int offset, 
    int count 
      

  7.   

    感谢几位大哥,问题解决
    用[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写
      

  8.   

    我在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