代码之家  ›  专栏  ›  技术社区  ›  user142350

在.NET中将结构转换为字节数组

  •  3
  • user142350  · 技术社区  · 15 年前

    我希望使用my.computer.filesystem.writeallbytes等将由固定长度字符串组成的结构写入文件。

    我正在使用一个带有固定长度字符串的vb6项目,该字符串已转换为vb.net。

        Structure Record
            <VBFixedString(22),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=22)> Public tim() As Char
            <VBFixedString(130),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=130)> Public des() As Char
            <VBFixedString(2),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=2)> Public crlf() As Char
        End Structure
    

    对于在C_中编组仍然是个新手,但是我如何将这个结构转换为一个字节数组以写入文件。是否有一些编组技巧,或者我必须编写一个自定义方法?

    1 回复  |  直到 15 年前
        1
  •  5
  •   Mehrdad Afshari    15 年前

    使用.NET框架提供的序列化机制:

    Dim formatter As New BinaryFormatter
    formatter.Serialize(outputFileStream, objectInstance)
    

    你应该增加 <Serializable()> 属性设置为您的类型。