C# 序列化与反序列化

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace Utility
{
    public class Serialization
    {
        // 序列化
        public static void EnS(string fileName = @"D:\test.xml", object obj = null)
        {
            fileName = Guid.NewGuid().ToString() + ".xml";
            obj = Guid.NewGuid();
            using (Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                using (XmlWriter writer = XmlWriter.Create(stream))
                {
                    try
                    {
                        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                        ns.Add(string.Empty, string.Empty);
                        XmlSerializer xmls = new XmlSerializer(obj.GetType());
                        xmls.Serialize(writer, obj, ns);
                    }
                    catch (Exception exp)
                    {
                        string message = string.Format("保存{0}时发生错误", obj.GetType().Name);
                        throw new Exception(message);
                    }
                }
            }
        }

        // 反序列化
        public static T Load<T>(string fileName = @"D:\test.xml")
        {
            using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                using (XmlReader reader = XmlReader.Create(stream))
                {
                    try
                    {
                        XmlSerializer xmls = new XmlSerializer(typeof(T));

                        return (T)xmls.Deserialize(reader);
                    }
                    catch (Exception exp)
                    {
                        string message = string.Format("装载{0}时发生错误", typeof(T).Name);
                        throw new Exception(message, exp);
                    }
                }
            }
        }
    }
}

 

C# 序列化与反序列化

上一篇:理解C#系列 / 核心C# / 枚举


下一篇:bzoj1026--SCOL2009--windy数(数位dp练习1)