c# 序列化和反序列化

 

 public static void Serialize(T entity)
        {
            TextWriter tw = new StringWriter();

            var formatter = new XmlSerializer(typeof(T));
            formatter.Serialize(tw, entity);

            if (!Directory.Exists(Path.GetDirectoryName(Filename)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(Filename));
            }
            File.WriteAllText(Filename, tw.ToString());
        }

        public static T Deserialize()
        {
            BaseFolder = RegistryDAO.GetRegistData("AirwayPatientsRootPath");
            Filename = Path.Combine(BaseFolder, "Ts.xml");
            if (!File.Exists(Filename))
            {
                Serialize(new T());
            }
            TextReader tr = new StringReader(File.ReadAllText(Filename));

            var formatter = new XmlSerializer(typeof(T));
            var entity = (AirwayPatients)formatter.Deserialize(tr);

            return entity;
        }

 

posted @ 2013-03-21 20:25  louiskoo  阅读(285)  评论(0编辑  收藏  举报