Serialize and Deserialize objects using .Net’s SoapFormatter
Suppose you want to serialize an object in your application to allow you to save it to a file or for some other reason. One option you have is to serialize it using .Net’s XML serialization.
I’m going to give you another option using the SoapFormatter class. These same techniques will also work using the BinaryFormatter class.
The first thing you will need to do is annotate the class you would like to serialize using the [System.SerializableAttribute()] and [System.Runtime.Serialization.OptionalFieldAttribute()] annotations.
[System.SerializableAttribute()]
public class MyClass
{
[System.Runtime.Serialization.OptionalFieldAttribute()]
public string Field1;
[System.Runtime.Serialization.OptionalFieldAttribute()]
public string Field2;
...
}
Here’s the serialize function that converts the object to a string:
public static string SerializeObject(object o)
{
if (o == null)
return null;
Stream stream = new MemoryStream();
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(stream, o);
StringBuilder s = new StringBuilder();
stream.Seek(0, SeekOrigin.Begin);
while (true)
{
int b = stream.ReadByte();
if (b == -1)
break;
s.Append(Convert.ToChar(b));
}
stream.Close();
return s.ToString();
}
And here’s the function that will deserialize the object:
public static Object DeserializeObject(string xml)
{
Object result = null;
try
{
Stream stream = new MemoryStream();
foreach (char c in xml.ToCharArray())
{
stream.WriteByte(Convert.ToByte(c));
}
stream.Seek(0, SeekOrigin.Begin);
SoapFormatter formatter = new SoapFormatter();
result = (Object)formatter.Deserialize(stream);
stream.Close();
}
catch
{
result = null;
}
return result;
}