Convert structure to byte array in .NET

倖福魔咒の 提交于 2019-12-10 19:43:36

问题


I wish to write a structure made up of fixed length strings to a file using My.Computer.FileSystem.WriteAllBytes or the like.

I am using a VB6 project with fixed length strings that I have converted in to 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

Still new to marshalling in C#, but how would I get this structure to an array of bytes to write to a file. Is there some marshalling trick or am I going to have to write a custom method?


回答1:


Use serialization mechanisms provided by the .NET framework:

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

You should add <Serializable()> attribute to your type.



来源:https://stackoverflow.com/questions/1288966/convert-structure-to-byte-array-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!