关于web.config的处理以及改进

来源:互联网 发布:淘宝电脑详情里加热点 编辑:程序博客网 时间:2024/05/02 08:36

一个修改web.config中appSettings配置节的函数

    这个函数主要使用XmlDocument来解析web.config.并用SelectSingleNode()方法来定位要修改的配置节。要注意的是最后程序要Save(),所以,你的apsnet帐号必须对web.config拥有写权限.


  /// <summary>
  ///  修改web.config文件appSettings配置节中的Add里的value属性
  /// </summary>
  /// <remarks>
  ///  注意,调用该函数后,会使整个Web Application重启,导致当前所有的会话丢失
  /// </remarks>
  /// <param name="key">要修改的键key</param>
  /// <param name="strValue">修改后的value</param>
  /// <exception cref="">找不到相关的键</exception>
  /// <exception cref="">权限不够,无法保存到web.config文件中</exception>
  public void Modify(string key,string strValue)
  {
   string XPath="/configuration/appSettings/add[@key='?']";
   XmlDocument domWebConfig=new XmlDocument();
   
   domWebConfig.Load( (HttpContext.Current.Server.MapPath("web.config")) );
   XmlNode addKey=domWebConfig.SelectSingleNode( (XPath.Replace("?",key)) );
   if(addKey == null)
   {
    throw new ArgumentException("没有找到<add key='"+key+"' value=.../>的配置节");
   }
   addKey.Attributes["value"].InnerText=strValue;
   domWebConfig.Save( (HttpContext.Current.Server.MapPath("web.config")) );
   
  }
//来源:http://blog.csdn.net/zjsen/archive/2004/06/28/28778.aspx

用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;
  }
 }
}//来源:
http://blog.csdn.net/chjl/archive/2004/06/29/29028.aspx

原创粉丝点击