码迷,mamicode.com
首页 > Windows程序 > 详细

C# 序列化与反序列化

时间:2015-01-18 22:32:42      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:

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# 序列化与反序列化

标签:

原文地址:http://www.cnblogs.com/mtsl/p/4232464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!