从discuz 里扒过来的一个通用序列化和反序列化类

感觉蛮好用的。我将一些常用的实体类型序列化成xml格式保存成xml,在系统运行时,先将其读取到缓存。

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Xml.Serialization;

using System.IO;

using System.Xml;



namespace HMYY.Common

{

    public class SerializationHelper

    {



        /* 字典,用来存储XmlSerializer 



       * 注意是此处是static 



       * 实际上起缓存的作用 



       */

        private static Dictionary<int, XmlSerializer> serializer_dict = new Dictionary<int, XmlSerializer>();



        /// <summary> 



        /// 为给予的类匹配一个XmlSerializer 对象, 



        /// 若之前就使用过,则从缓存里调出来,若没有, 



        /// 则新建一个对应的XmlSerializer 对象。 



        /// </summary> 



        /// <param name="t">给予的类</param> 



        /// <returns></returns> 

        public static XmlSerializer GetSerializer(Type t)

        {

            //先获得type 的哈希值,作为字典的索引 

            int type_hash = t.GetHashCode();

            //如果字典里没有这个type的哈希,就创建一个,放到字典表里 



            if (!serializer_dict.ContainsKey(type_hash))



                serializer_dict.Add(type_hash, new XmlSerializer(t));



            //查询到这个哈希对应的对象,传出去 

            return serializer_dict[type_hash];

        }



        /// <summary>

        /// 反序列化

        /// </summary>

        /// <param name="type">对象类型</param>

        /// <param name="filepath">文件路径</param>

        /// <returns></returns>

        public static object Load(Type type, string filepath)

        {

            FileStream fs = null;

            try

            {

                fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);

                XmlSerializer serializer = new XmlSerializer(type);

                return serializer.Deserialize(fs);

            }

            catch(Exception ex)

            {

                throw ex;

            }

            finally

            {

                if (fs != null)

                {

                    fs.Close();

                    fs.Dispose();

                }

            }





        }



        /// <summary>

        /// 序列化

        /// </summary>

        /// <param name="obj">对象</param>

        /// <param name="filename">文件路径</param>

        public static bool Save(object obj, string filepath)

        {

            bool Isok = false;

            FileStream fs = null;

            try

            {

                fs = new FileStream(filepath, FileMode.Create, FileAccess.Write);

                XmlSerializer serializer = new XmlSerializer(obj.GetType());

                serializer.Serialize(fs, obj);

                Isok = true;

            }

            catch(Exception ex)

            {

                throw ex;

            }

            finally

            {

                if (fs != null)

                {

                    fs.Close();

                    fs.Dispose();

                }

            }



            return Isok;

        }





        /// <summary> 



        /// xml序列化成字符串 



        /// </summary> 



        /// <param name="obj">对象</param> 



        /// <returns>xml字符串</returns> 



        public static string Serialize(object obj)

        {



            string returnStr = "";



            XmlSerializer serializer = GetSerializer(obj.GetType());



            // 实例化一个内存流 



            MemoryStream ms = new MemoryStream();



            XmlTextWriter xtw = null;



            StreamReader sr = null;



            try

            {



                //实例化一个xml的写对象,其中使用utf-8 编码,写入到刚实例化的内存流中去 



                xtw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8);



                //设置缩进方式 



                xtw.Formatting = System.Xml.Formatting.Indented;







                //序列化它 



                serializer.Serialize(xtw, obj);



                /* 



                 * 此时内存流已经指向写完的地方, 



                 * 要再次读取到这个内存里的内容, 



                 * 需要将其"指针"指向内存流的开始 



                 * 下面一句就是做这个事情 



                 * param1  针对param2 的偏移量, 



                 * param2  内存开始的地方 



                 */



                ms.Seek(0, SeekOrigin.Begin);



                //实例化一个流阅读器,去读内存流 



                sr = new StreamReader(ms);



                returnStr = sr.ReadToEnd();



            }



            catch (Exception ex)

            {



                throw ex;



            }



            finally

            {



                if (xtw != null)



                    xtw.Close();



                if (sr != null)



                    sr.Close();



                ms.Close();



            }



            return returnStr;







        }







        /// <summary> 



        /// 反序列化 ,通过一个string 



        /// </summary> 



        /// <param name="type">反序列化的类的类型</param> 



        /// <param name="s">序列源</param> 



        /// <returns></returns> 



        public static object DeSerialize(Type type, string s)

        {



            /* 



             * 此处将字符串转化为byte数组 



             * 其中值得注意的是,使用UTF-8 编码 



             * 就可以回避因为是非ASCII码被解析成乱码了 



             */



            byte[] b = System.Text.Encoding.UTF8.GetBytes(s);



            try

            {



                XmlSerializer serializer = GetSerializer(type);



                return serializer.Deserialize(new MemoryStream(b));



            }



            catch (Exception ex)

            {



                throw ex;



            }



        } 









    }

}



 

你可能感兴趣的:(discuz)