Binary and XML Serialization - Binary Serialization continued
(Page 3 of 4 )
Note: in order to use theBinaryFormatter, make sure you add the following "using" statements:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
Now that the content of the object is stored in the file, you can retrieve it later on in the application by deserializing the object. We can use theDesialize()method from theBinaryFormatterclass. Here is the method:
private static Book DeserializeBook()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("book.bin", FileMode.Open,
FileAccess.Read, FileShare.Read);
Book b = (Book)formatter.Deserialize(stream);
stream.Close();
return b;
}
We create the usual objects: aBinaryFormatterto deserialize the content, and a FileStreamobject (but for reading this time). When deserializing the stream, make sure the result is cast to the appropriate object type (Bookin this case).
Finally, we can create aBookobject and callSerializeBook()andDeserializeBook()in the main method as follows:
static void Main(string[] args)
{
Book favoriteBook = new Book("0-7356-2527-1",
"Programming with ASP.NET 3.5","Dino Esposito");
Console.WriteLine("Serializing Book...");
SerializeBook(favoriteBook);
Console.WriteLine("Book serialized");
Console.WriteLine("Deserializing Book...");
Book myBook = DeserializeBook();
Console.WriteLine(myBook); //calling ToString()
Console.ReadLine();
}
After serializing theBookobject, the content of the file might look like the following:
˙˙˙˙ JBinarySerialization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null BinarySerialization.Book isbntitleauthor
0-7356-2527-1 Programming with ASP.NET 3.5
Dino Esposito
This look like garbage data, but you can see the title and the author strings. This is about it as far as serializing and deserializing objects using theBinaryFormatter, which is very powerful but limited to .NET applications.
Some classes might contain sensitive information that you would rather not serialize. To handle this, just tag the appropriate field with the[NonSerialized]attribute, like so:
[NonSerialized] public int id;
This will inform .NET to ignore this field when serializing the object.
It is very important to note that every member in the class will be serialized, including private members. If that is an issue, then you need to look at XML serialization. Equally as important, the constructor is not called when an object is deserialized for performance reasons.
Next: XML Serialization >>
More .NET Articles
More By Ayad Boudiab