.NET provides a functionality for storing and loading objects. This post shows how it can be used. The mechanism is called serialization and its purpose is to convert any object to stream of bytes that can be saved on a disk, sent by a protocol via internet etc.
So, at the beginning you have a class which you want to serialize. For example it looks like this:
Now, you want to save object of this class on a disk. At first add some namespaces:
[Serializable]attribute to your class:
and then add methods for save and load in
Here is an example how to use these methods:
That is all. It is very simple to use.
Note: Instead of
BinaryFormatteryou can use
The code is the same, only replace
System.Runtime.Serialization.Formatters.Soapnamespace. For this namesapce you have to add reference to
System.Runtime.Serialization.Formatters.Soap.dllassembly in your project.
The difference is in the saved file. With
SoapFormatteryou get a file that is human readable. For our example, the saved file contains:
Notice how the reference-typed objects are stored.
Anyone can change the content of this file and the object will reflect these changes after deserialization.