C#使用SoapFormatter序列化对象

本文介绍如何在C#中使用SoapFormatter进行对象序列化,展示了一个StudentData类的实例,以及如何保存该对象到"data.soap"文件。通过SoapFormatter.Serialize方法将对象写入文件,生成的SOAP格式数据包含了对象的所有属性信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Serializable]
    public class StudentData
    {
        public string id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
    }

static void Main(string[] args)
        {
            try
            {

                StudentData data = new StudentData() { id = "001", name = "西门吹雪", age = 40 };

                SaveData(data);
                System.Console.WriteLine("end");

            }catch(Exception ex)
            {
                System.Console.WriteLine("Message: " + ex.Message);
                System.Console.WriteLine("StackTrace: " + ex.StackTrace);
                System.Console.WriteLine("Name: " + ex.TargetSite.Name);
            }
            System.Console.ReadLine();
        }

        static void SaveData(object obj)
        {
            SoapFormatter soapFormatter = new SoapFormatter();

            using(Stream stream = new FileStream("data.soap",FileMode.Create,FileAccess.Write,FileShare.None))
            {
                soapFormatter.Serialize(stream, obj);
            }
        }

   结果:

<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:StudentData id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/Frensworkz.ConsoleApplication/Frensworkz.ConsoleApplication%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
   <_x003C_id_x003E_k__BackingField id="ref-3">001</_x003C_id_x003E_k__BackingField>
   <_x003C_name_x003E_k__BackingField id="ref-4">西门吹雪</_x003C_name_x003E_k__BackingField>
   <_x003C_age_x003E_k__BackingField>40</_x003C_age_x003E_k__BackingField>
 </a1:StudentData>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值