3

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?

2
  • As a side note, a structure is not a reference type. It's a value type. Commented Aug 17, 2009 at 18:25
  • 1
    Changed in title. I knew that but for some reason still wrote reference. Commented Aug 17, 2009 at 19:00

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@dnh828, To add to @Mehrdad's answer, also make sure all the types in the object graph you are trying to convert are decorated with the [Serializable] attribute...
How do I apply the serializable attribute to these fixed length strings?
You don't need to. Just apply it to the Structure. Char arrays are serializable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.