序列化和反序列化

代码:

internal static class Class1
{
    private static readonly string XML_FOLDER = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "CompanyName", "ProjectName");
    private static readonly string XML_FILE = Path.Combine(XML_FOLDER, "config.xml");

    static Class1()
    {
        if (!Directory.Exists(XML_FOLDER))
        {
            Directory.CreateDirectory(XML_FOLDER);
        }
    }

    internal static T Deserialize<T>()
    {
        return (T)new XmlSerializer(typeof(T)).Deserialize(new FileStream(XML_FILE, FileMode.OpenOrCreate, FileAccess.ReadWrite));
    }
    internal static void Serialize(this object obj)
    {
        new XmlSerializer(obj.GetType()).Serialize(new FileStream(XML_FILE, FileMode.Create, FileAccess.ReadWrite), obj);
    }
}

用法:

new List<string> { "asd", "dfd" }.Serialize();
var a = Class1.Deserialize<List<string>>();

 

internal static class Class3
{
    private static readonly string XML_FOLDER = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "CompanyName", "ProjectName");
    private static readonly string XML_FILE = Path.Combine(XML_FOLDER, "config.xml");

    static Class3()
    {
        if (!Directory.Exists(XML_FOLDER))
        {
            Directory.CreateDirectory(XML_FOLDER);
        }
    }

    internal static T Deserialize<T>()
    {
        using (var stream = new FileStream(XML_FILE, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            return (T)new XmlSerializer(typeof(T)).Deserialize(stream);
        }
    }
    internal static void Serialize(this object obj)
    {
        using (var stream = new FileStream(XML_FILE, FileMode.Create, FileAccess.ReadWrite))
        {
            new XmlSerializer(obj.GetType()).Serialize(stream, obj);
        }
    }
}

 

posted on 2013-07-20 21:50  yao2yao4  阅读(210)  评论(0编辑  收藏  举报

导航