Object Serialization/Deserialization


Download working sourcecode example C# Console project from here, or here {29.4 Kb}


Serialization:



FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);

try {

   BinaryFormatter bFormatter = new BinaryFormatter();
   bFormatter.Serialize(fs, myObject);
                         
} catch (Exception exception) {

    MessageBox.Show(exception.Message);

} finally {

    if (fs != null) {
        fs.Close();
    }
}




Deserialization:



FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read, FileShare.None);

try {
    BinaryFormatter bFormatter = new BinaryFormatter();
    myObject = (myObject)bFormatter.Deserialize(fs);           
} catch (Exception exception) {
    MessageBox.Show(exception.Message);                    
} finally {
    if (fs != null) {
        fs.Close();
    }
}