用XmlSerializer为ASP.NET打造配置文件

在ASP.NET的配置文件Web.config中,可以方便加入自定义键值对。如下:
<configuration>
 <appSettings>
  <add key="myKey" value="myValue">
 </appSettings>
</configuration>

需要时可以这样取出值。
string myValue = System.Configuration.ConfigurationSettings.AppSettings["myKey"];

但是web.config中的内容如被更改会使整个HttpApplication重启,在Web.config中存放频繁更改的数据就不适合了。

下面我介绍一个方法,同样利用XML格式保存数据,文件格式如下:
Password.config

<?xml version="1.0" encoding="gb2312"?>
<configuration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <settings xmlns="http://www.cjl.cn">
    <add key="name1" value="MyPassword" />
    <add key="name2" value="b" />
  </settings>
</configuration>

很明显,我们可以加入任意的<add>。我们可以这样通过key取值。

string configFile = this.MapPath("Password.config");
ConfigSetting cs = ConfigSetting.GetSetting(configFile);
string password = cs["name1"];

请看下页这个关键的类
using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Collections;
using System.Xml.Serialization;
using System.Text;

namespace cjl.Web.Configuration
{
 [
 XmlType(Namespace = "http://ajliang.126.com", TypeName = "configuration")
 ]
 public class ConfigSetting
 {
  Setting settings;
  public ConfigSetting()
  {
  }

  public string this[string key]
  {
   get
   {
    return this.Settings[key];
   }
   set
   {
    this.Settings[key] = value;
   }
  }
 
  [XmlElement(ElementName = "settings")]
  public Setting Settings
  {
   get
   {
    if (settings == null)
    {
     settings = new Setting();
    }
    return settings;
   }
   set
   {
    settings = value;
   }
  }


  public void SaveSetting(string xmlFile)
  {
   XmlSerializer serializer = new XmlSerializer (this.GetType());
  
   FileStream fs = new FileStream(xmlFile, FileMode.Create);
   StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312"));
   serializer.Serialize(sw, this);
   sw.Close();
  }

  public static ConfigSetting GetSetting(string xmlFile)
  {
   HttpContext context = HttpContext.Current;
   object s = context.Cache[xmlFile];
   if (s == null)
   {
    XmlSerializer serializer = new XmlSerializer(typeof(ConfigSetting));
    FileStream fs = new FileStream(xmlFile, FileMode.Open); 
    s = serializer.Deserialize(fs);
    fs.Close();
    context.Cache.Insert(xmlFile, s, new CacheDependency(xmlFile));
   }

   return (ConfigSetting) s;
  }

  public class Setting
  {
   Add[] adds;
   [XmlElement(ElementName = "add")]
   public Add[] Adds
   {
    get
    {
     return adds;
    }
    set
    {
     adds = value;
    }
   }

   public string this[string key]
   {
    get
    {
     if (adds == null)
     {
      throw new Exception("没有Add元素");
     }
     string str = null;
    
     foreach (Add add in adds)
     {
      if (add.Key == key)
      {
       str = add.Value;
       break;
      }
     }
    
     if (str == null)
     {
      throw new Exception("没有元素Add的属性key=" + key + "。");
     }
     return str;
    }
    set
    {
     if (adds == null)
     {
      Add a = new Add();
      a.Key = key;
      a.Value = value;
      adds = new Add[] {a};
      return;
     }
     foreach (Add aa in adds)
     {
      if (aa.Key == key)
      {
       aa.Value = value;
       return;
      }
     }
     Add aaa = new Add();
     aaa.Key = key;
     aaa.Value = value;
     Add[] myAdds = new Add[adds.Length + 1];
     adds.CopyTo(myAdds, 0);
     myAdds[myAdds.Length - 1] = aaa;
     adds = myAdds;
    }
   } // public string this[string str]


  } // public class Setting

  public class Add
  {
   [XmlAttribute(AttributeName = "key")]
   public string Key;
   [XmlAttribute(AttributeName = "value")]
   public string Value;
  }


 } //

} // namespace cjl.Configuration

保存,修改,添加的演示代码参考如下
WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="TestConfigSetting.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
 <head>
  <title>WebForm1</title>
  <meta name="GENERATOR" content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </head>
 <body>
  <form id="Form1" method="post" runat="server">
   ConfigFile:<asp:textbox id="ConfigFile" runat="server" text="Password.config"></asp:textbox><br>
   <asp:button id="Save" runat="server" text="新建一个配置文件"></asp:button>
   <asp:button id="GetAllKeyValueByFile" runat="server" text="通过配件文件显示所有键值对"></asp:button><br>
   <br>
   Key:<asp:textbox id="Key" runat="server" text="name1"></asp:textbox>Value:<asp:textbox id="Value" runat="server" value="MyPassword"></asp:textbox><br>
   <asp:button id="GetValueByKey" runat="server" text="通过键取得值"></asp:button><asp:button id="UpdateValueByKey" runat="server" text="通过键更新或添加值(如果没有存在的键将添加)"></asp:button><br>
   <br>
   结果如下:<hr>
   <asp:label id="Message" runat="server"></asp:label>
  </form>
 </body>
</html>


WebForm1.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using cjl.Web.Configuration;

namespace TestConfigSetting
{
 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.TextBox Key;
  protected System.Web.UI.WebControls.TextBox ConfigFile;
  protected System.Web.UI.WebControls.Button GetAllKeyValueByFile;
  protected System.Web.UI.WebControls.Button GetValueByKey;
  protected System.Web.UI.WebControls.Button Save;
  protected System.Web.UI.WebControls.TextBox Value;
  protected System.Web.UI.WebControls.Button UpdateValueByKey;
  protected System.Web.UI.WebControls.Label Message;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   InitializeComponent();
   base.OnInit(e);
  }
 
  private void InitializeComponent()
  {   
   this.Save.Click += new System.EventHandler(this.Save_Click);
   this.GetAllKeyValueByFile.Click += new System.EventHandler(this.GetAllKeyValueByFile_Click);
   this.GetValueByKey.Click += new System.EventHandler(this.GetValueByKey_Click);
   this.UpdateValueByKey.Click += new System.EventHandler(this.UpdateValueByKey_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void GetValueByKey_Click(object sender, System.EventArgs e)
  {
   string configFile = this.MapPath(ConfigFile.Text.Trim());
   ConfigSetting cs = ConfigSetting.GetSetting(configFile);
   string message = "";
   try
   {
    message = Key.Text.Trim() + " = " + cs[Key.Text.Trim()];
   }
   catch (Exception ex)
   {
    message = ex.ToString();
   }
   Message.Text = message;
  
  }

  private void GetAllKeyValueByFile_Click(object sender, System.EventArgs e)
  {
   string configFile = this.MapPath(ConfigFile.Text.Trim());
   ConfigSetting cs = ConfigSetting.GetSetting(configFile);

   string message = "";
   foreach (ConfigSetting.Add add in cs.Settings.Adds)
   {
    message += add.Key + " = " + add.Value + "<br>";
   }
   Message.Text = message;
  }

  private void Save_Click(object sender, System.EventArgs e)
  {
   string configFile = this.MapPath(ConfigFile.Text.Trim());
   ConfigSetting cs = new ConfigSetting();
   cs["name1"] = "a";
   cs["name2"] = "b";
   cs.SaveSetting(configFile);
   Message.Text = "已经保存到: " + configFile;

  }

  private void UpdateValueByKey_Click(object sender, System.EventArgs e)
  {
   string configFile = this.MapPath(ConfigFile.Text.Trim());
   ConfigSetting cs = ConfigSetting.GetSetting(configFile);
   cs[Key.Text.Trim()] = Value.Text;
   cs.SaveSetting(configFile);
   Message.Text = "更新成功: " + configFile;
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值