Binary file IO

Runtime_error

Active member
Joined
Aug 5, 2003
Messages
38
Hi I need some advice and possibly some help as well with Writing Binary data to files.

I have to output the data to a file in binary format into a predefined structure (not the programming Struct ). So basically the data in the file is organised in a known format.

File Header
Main Contents
.....

Please have a look at the following Code

Code:
[StructLayout(LayoutKind.Sequential)]
struct SomeFileHeader
{
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
   public string Signature;
   public Int32 Offset;
   public Int32 Length;
}

public static byte[] RawSerialize( object anything )
 {
       int rawsize = Marshal.SizeOf( anything );
       IntPtr buffer = Marshal.AllocHGlobal( rawsize );
       Marshal.StructureToPtr( anything, buffer, false );
       byte[] rawdatas = new byte[ rawsize ];
       Marshal.Copy( buffer, rawdatas, 0, rawsize );
       Marshal.FreeHGlobal( buffer );
       return rawdatas;
 }

If i pass the struct into the above function and then write the returned bytes to a file using the binarywriter then Will i have just the data from the structure ? or will a lot of .net stuff be written into the file as well.

Like i said the requirement is simply to store the data in the file not the structure of the STRUCT. Thanks
 
Last edited by a moderator:
Well, I did a quick test:
I declared a bipole structure (dont ask why) with two ints and a marshalled T-string with size 4.
Code:
Bp.UpAxis = 65536
Bp.ImaginaryReflect = 16777215
Bp.Lab = "axis"
And checked the bytes returned:
0 0 1 0 255 255 255 0 97 120 105 0
which is:
0 0 1 0 = 65536
255 255 255 0 = 16777216
97 120 105 0 = "axi\0"
So, yes if you write a byte array to a file, then the byte array itself will be in the file, nothing extra added on to it... Although, I probably wouldve just copied 4 characters from the end of the string with a binarywriters (Char[], Int index, Int count) overload.
And yes, write to a file with binarywriter, read with binaryreader. :)
I hope that helped.
 
Thank you for your reply, I also did the same test as u after i wrote the post.

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]

That limits the string output to first four bytes one of them is the null char.
I think it all looks good, and now i can go ahead writing the File Struct.

Thank you for your reply :)

A Coder in need is a Coder indeed or something like that :D
 
Back
Top