SoapFormatter in C#

It's stored in this path.

["Your Drive"] : \ Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\ [".Net version"] \Profile\Client\

SOAPFormatter implements the IFormatter interface which has 2 functions named Serialize and Deserialize to do the job for you.

Serializer takes two arguments

Stream and Object.

Stream argument depends on the file to be serialized to and Object argument tells us which object is going to be processed.it can be any type of list since it's an object. But we preferred using a List of string values.

Note. SoapFormatter doesn't accept generic lists such as List<T>. Alright, let's create a new project in Visual Studio and see how it works: Add Reference to the "System.Runtime.Serialization.Formatters.Soap" which is stored in the path i gave above. Then add these namespaces to your project.

using System.IO;  
using System.Collections;  
using System.Runtime.Serialization.Formatters.Soap; 

After that create 2 functions for the serialization and deserialization to the file.

private static void Serializer(ArrayList list)
{
}
private static ArrayList Deserializer()
{
}

Now create a file named "users.soap" to store the object to be serialized to and Serialize it!

private static void Serializer(ArrayList list)
{
    using (FileStream fs = File.Create("users.soap"))
    {
        SoapFormatter sof = new SoapFormatter();
        sof.Serialize(fs, list);
    }
}

Then for the Deserialization, you've to open this file in OpenRead mode for deserializing and rebuilding the file that's serialized.

private static void Serializer(ArrayList list)
{
    using (FileStream fs = File.Create("users.soap"))
    {
        SoapFormatter sof = new SoapFormatter();
        sof.Serialize(fs, list);
    }
}

Now, let's add some values to our ArrayList object, serialize, and deserialize it to rebuild the users.soap file.

ArrayList users = new ArrayList();
users.Add("Ibrahim Ersoy");
users.Add("Gandalf");
users.Add("Sauron");
users.Add("Mouth Of Sauron - The Funny Guy");
Serializer(users);
ArrayList userlist = Deserializer();

To get the results we can use a foreach to iterate the requested kind of information according to the data types.

foreach (string s in userlist)
    textBox1.Text += s + Environment.NewLine;

After you run and test it, you'll see that your file has been created and is ready to work.

Created and ready


Recommended Free Ebook
Similar Articles