序列化与反序列化读取保存xml文件

Common:

/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">对象类型</param>
/// <param name="filename">文件路径</param>
/// <returns></returns>
public static object Load(Type type, string filename)
{
   FileStream fs = null;
   try
   {
      // open the stream...
      fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
      XmlSerializer serializer = new XmlSerializer(type);
      return serializer.Deserialize(fs);
   }
   catch (Exception ex)
   {
      throw ex;
   }
   finally
   {
      if (fs != null)
      fs.Close();
   }
}
/// <summary> /// 序列化 /// </summary> /// <param name="obj">对象</param> /// <param name="filename">文件路径</param> public static void Save(object obj, string filename) { FileStream fs = null; // serialize it... try { fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(fs, obj); } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); }
}

BLL:

private readonly Voda.DAL.WebSet dal = new Voda.DAL.WebSet();
/// <summary>
///  读取配置文件
/// </summary>
/// <param name="configFilePath"></param>
/// <returns></returns>
public Voda.Model.WebSet loadConfig(string configFilePath)
{
   return dal.loadConfig(configFilePath);
}
/// <summary>
///  保存配置文件
/// </summary>
/// <param name="mode"></param>
/// <param name="configFilePath"></param>
/// <returns></returns>
public Voda.Model.WebSet saveConifg(Voda.Model.WebSet mode, string configFilePath)
{
   return dal.saveConifg(mode, configFilePath);
}

DAL:

private static object lockHelper = new object();
/// <summary> /// 读取xml文件 /// </summary> /// <param name="configFilePath"></param> /// <returns></returns> public Voda.Model.WebSet loadConfig(string configFilePath) { return (Voda.Model.WebSet)Tool.SerializationHelper.Load(typeof(Voda.Model.WebSet), configFilePath); }
public Voda.Model.WebSet saveConifg(Voda.Model.WebSet mode, string configFilePath) { lock (lockHelper) { Tool.SerializationHelper.Save(mode, configFilePath); } return mode; }

 WEB:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
       //获取web.config下Configpath节点的xml路径
       model=websetBLL.loadConfig(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Configpath"].ToString()));
   }
}

 Web.Config:

<appSettings>
   <add key="Configpath" value="所要读取的XML路径"/>
</appSettings>

 

 

 

 

 

 

posted @ 2012-06-05 11:46  Setme  阅读(1170)  评论(0编辑  收藏  举报