Dennis,
While this might do it, if the structure contains pointers, it is not
going to accurately write the structure, as it won't know how to dereference
the pointer information. Also, this assumes that the structure can be
marshaled correctly across the managed/unmanaged boundary (which is also
more expensive).
I would recommend appending the Serializable attribute to the structure,
and then passing the structure to a BinaryFormatter (for a compact, fast,
format) or a SoapFormatter (for an XML document), and use that.
If your structure isn't complex, you could even use the XmlSerializer.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Dennis Myr? said:
I think this will do it:
byte [] buff = null;
unsafe
{
buff = new byte [sizeof(MyStruct)];
}
IntPtr ptr = Marshal.AllocHGlobal(buff.Length);
Marshal.StructureToPtr(myStruct, ptr, true);
Marshal.Copy(ptr, buff, 0x0, buff.Length);
Marshal.FreeHGlobal(ptr);
FileStream fs = new FileStream("C:\\MyStruct.bin", FileMode.Create,
FileAccess.Write, FileShare.None);
fs.Write(buff, 0x0, buff.Length);
fs.Close();
Dae-Suk Chung said:
Hi,
What is the easiest way to write a struct(with biary data) to a file ?
do I need to covert it through e.g. Marshal class ?
Thanks for any tips!
DaeSuk.