How to Deserialize an Object in C#

1. Create a stream object to read the serialized output.
2. Create a BinaryFormatter object.
3. Create a new object to store the deserialized data.
4. Call the BinaryFormatter.Deserialize method to deserialize the object, and cast it to the correct type.

// Open file from which to read the data
FileStream fs = new FileStream("SerializedString.Data", FileMode.Open);
 
// Create a BinaryFormatter object to perform the deserialization
BinaryFormatter bf = new BinaryFormatter();
 
// Create the object to store the deserialized data
string data = "";
 
// Use the BinaryFormatter object to deserialize the data from the file
data = (string)bf.Deserialize(fs);
 
// Close the file
fs.Close();
// Display the deserialized string
Console.WriteLine(data);

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.