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);
                    }
                }
            }
        }
    }
}

 

posted @ 2015-01-18 22:11  astrue  阅读(209)  评论(0编辑  收藏  举报