XmlSerialize

以前配置文件都直接写在TXT文件,能看懂就行;

后来写了点代码,就把配置写在ini文件里;

再后来随着趋势就把配置类序列化到本地,即xml配置;

现在懒了,直接ToJson到本地,需要时FromJson。

===== 2017.7.1===== 下面纪念下xml序列化

using System.IO;
using System.Xml.Serialization;

namespace Downloader
{
    public static class SerializeCfg
    {
        public static T DeserializeConfig<T>(this string path)
        {
            T result;
            using (FileStream fs = File.OpenRead(path))
            {
                //读取文件
                int nLength = (int)fs.Length;
                byte[] byteArray = new byte[nLength];
                fs.Read(byteArray, 0, nLength);

                using (MemoryStream stream = new MemoryStream(byteArray))
                {
                    //返序列化
                    XmlSerializer reader = new XmlSerializer(typeof (T));
                    result = (T) reader.Deserialize(stream);
                }
            }
            return result;
        }

        /// <summary>
        /// 序列化服务到持久设备
        /// </summary>
        public static void SerializeConfig<T>(this T obj, string path)
        {
            //序列化到内存
            XmlSerializer writer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                writer.Serialize(ms, obj);

                byte[] byteArray = ms.ToArray();

                //保存数据到文件
                using (FileStream fs = File.Create(path))
                {
                    fs.Write(byteArray, 0, byteArray.Length);
                }
            }

        }
    }
}

 

posted on 2017-07-01 06:09  jonney_wang  阅读(624)  评论(0编辑  收藏  举报

导航