By using SoapFormatter we can serialize object into SOAP format which can use to distribute objects across diverse environments. That means if you want to share serialize object through web service we have to use SoapFormatter. In this article we discuss about how to serialize object using SoapFormatter.
Open Microsoft Visual Studio 2013 => Add Reference to System.Runtime.Serialization.Formatters.Soap.dll as shown below
Add Employee.cs class as shown below.
using System;
namespace SoapFormatterSerialization
{
[Serializable]
class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
}
As shown above Employee class marked as serializable. Let’s serialize the object using SoapFormatter as shown below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SoapFormatterSerialization
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Employee objEmp = new Employee();
objEmp.EmployeeId = 1001;
objEmp.EmployeeName = "AAA";
SaveAsSoapFormat(objEmp, "E:\\Employee.soap");
}
static void SaveAsSoapFormat(object obj, string sFileName)
{
SoapFormatter objSoapFormat = new SoapFormatter();
using (Stream fStream = new FileStream(sFileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
objSoapFormat.Serialize(fStream, obj);
}
}
}
}
As shown above we created the object Employee class and serialize the Employee object using SoapFormatter. The serialized object saved in E drive as Employee.soap file. The Employee.soap content as shown below.
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<a1:Employee id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/SoapFormatterSerialization/SoapFormatterSerialization%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<_x003C_EmployeeId_x003E_k__BackingField>1001</_x003C_EmployeeId_x003E_k__BackingField>
<_x003C_EmployeeName_x003E_k__BackingField id="ref-3">AAA</_x003C_EmployeeName_x003E_k__BackingField>
</a1:Employee>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>