Writing a structure to a file (writing it as binary data)

  • Thread starter Thread starter Mufasa
  • Start date Start date
M

Mufasa

Here's a really stupid question - I have a class that I want to write to a
file to retrieve later (I've already made the class serialable ). How do you
do that? I can't find anything that will let me write out an entire class at
once?

TIA - Jeff.
 
Jeff,

The IFormatter interface (which BinaryFormatter and SoapFormatter both
implement) has two methods, Serialize and Deserialize which take streams
write to and read from. You can easily pass a FileStream instance to these
to write your serialized instance to, and read from.
 
MemoryStream stream = new MemoryStream();
BinaryFormatter bformatter = new BinaryFormatter();

MyClass myClass = new MyClass();

bformatter.Serialize(stream, myClass);

FileStream fs = new FileStream("MyBackUpFile.bin",
FileMode.CreateNew);

using (BinaryWriter br = new BinaryWriter(fs))
{
br.Write(stream.ToArray());
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top