将结构转换为.NET中的字节数组 [英] Convert structure to byte array in .NET

查看:137
本文介绍了将结构转换为.NET中的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用My.Computer.FileSystem.WriteAllBytes等将由固定长度的字符串组成的结构写入文件.

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

我正在使用VB6项目,该项目具有固定长度的字符串,这些字符串已转换为VB.Net.

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

在C#中编组仍然是新手,但是我如何将这种结构转换为字节数组以写入文件.有编组技巧吗?还是我必须写一个自定义方法?

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?

推荐答案

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

Use serialization mechanisms provided by the .NET framework:

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

您应在类型中添加<Serializable()>属性.

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

这篇关于将结构转换为.NET中的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆