Object Serialization/Deserialization

back to Errata index


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


Serialization:



FileStream fStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);

try {

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

    MessageBox.Show(exception.Message);

} finally {

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




Deserialization:



FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None);

try {

    BinaryFormatter bFormatter = new BinaryFormatter();
    myObject = (myObject)bFormatter.Deserialize(fStream);
                
} catch (Exception exception) {

    MessageBox.Show(exception.Message);
                    
} finally {

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