Persistent objects by serializing

The object and all its components must have the attribute [Serializable]

 

How to read a [Serializable] object from a file

 

string myFilename = @"C:/temp/myfilemane.bin";

System.IO.FileStream  fileStream =

new System.IO.FileStream(myFilename, System.IO.FileMode.Open);

 

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter   binaryFormater =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

 

MyClass myObject = (MyClass)binaryFormater.Deserialize(fileStream);

   

fileStream.Close();

  

How to write a [Serializable] object to a file

 

string myFilename = @"C:/temp/myfilemane.bin";

System.IO.FileStream  fileStream =

new System.IO.FileStream(myFilename,System.IO.FileMode.Create);

 

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter   binaryFormater =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

 

binaryFormater.Serialize(fileStream, myObject);

 

fileStream.Close();

   

Defining serializable objects

  

[Serializable]

class MyClassComponent

{

........

}

 

[Serializable]

class MyClass

{

MyClassComponent  componentObject ........

}

 

If you write a MyClass object to a file, all objects referenced also will be written.

The trick is:

Having one "top"-object with references to the other objects (direct or indirect) as the business-model.

When you save the "top" object, the hole business-model will be saved.

When you later read the "top"-object, the “top”-object and all the referenced objects (business-model) will be read into the memory again.