Convert structure to byte array in .NET.

I want to write a structure consisting 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 converted 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 for sorting in C #, but how can I get this structure into an array of bytes for writing to a file. Is there any marshalling trick or will I have to write my own method?

+3
source share
1 answer

Use the serialization mechanisms provided by the .NET platform:

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

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

+5
source

Source: https://habr.com/ru/post/1715345/


All Articles