读书笔记:《亮剑 .Net》——将类转化为XML并保存已经去读后反序列化为类对象

简历一个可序列化的类

 

///   <summary>
    
///  配置的Modul类,即:保存的配置项(可以自定义成自己的项)
    
///  注意相关属性的类型与[XmlElement]
    
///   </summary>
     public   class  ModuleSettings
    {
        
private   string  server;
        
private   string  username;
        
private   string  password;
        
private   string  database;
        

        [XmlElement]
        
public   string  Server
        {
            
set  { server  =  value; }
            
get  {  return  server; }
        }
        [XmlElement]
        
public   string  UserName
        {
            
set  { username  =  value; }
            
get  {  return  username; }
        }
        [XmlElement]
        
public   string  Password
        {
            
set  { password  =  value; }
            
get  {  return  password; }
        }
        [XmlElement]
        
public   string  Database
        {
            
set  { database  =  value; }
            
get  {  return  database; }
        }
    }

 

序列化后保存

 

public   static   void  SaveSettings(ModuleSettings data)
        {
            
string  fileName  =  HttpContext.Current.Server.MapPath(GetSettingsFile());
            XmlSerializer serializer 
=   new  XmlSerializer( typeof (ModuleSettings));

            
//  serialize the object
            FileStream fs  =   new  FileStream(fileName, FileMode.Create);
            serializer.Serialize(fs, data);
            fs.Close();
        }

 

读取后反序列化

 

 

// 得到配置项对象实例信息
         public   static  ModuleSettings GetSettings()
        {
            XmlSerializer serializer 
=   new  XmlSerializer( typeof (ModuleSettings));
            
try
            {
                    
// 从文件取
                 string  fileName  =  HttpContext.Current.Server.MapPath(GetSettingsFile());
                FileStream fs 
=   new  FileStream(fileName, FileMode.Open);                    
                
return  data  =  (ModuleSettings)serializer.Deserialize(fs); // 反序列化
                fs.Close();
            }
            
catch  (System.IO.FileNotFoundException)
            {
                    
// 如果文件不存在,则返回一个空对象
                 return  data  =   null
            }
        }

你可能感兴趣的:(.net)