利用程序动态管理Web.config文件的配置

Web.config文件假设有如下需要管理的配置信息:   

<appSettings>
<add key="Sitetitle" value="站点名称" />
<add key="SiteUrl" value="主页网址" />
<add key="SiteLogo" value="站点Logo" />
<add key="SiteBanner" value="站点Banner" />
<add key="SiteEmail" value="联系Email" />
</appSettings>

实现的c#核心代码:
一、将Web.config中的相关信息读入TextBox

 1 private void Page_Load(object sender, System.EventArgs e)
2 {
3 if(!Page.IsPostBack)
4 {
5 //将Web.config中的相关值填入TextBox
6 this.txttitle.Text=System.Configuration.ConfigurationSettings.AppSettings["Sitetitle"];
7 this.txtUrl.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteUrl"];
8 this.txtLogo.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteLogo"];
9 this.txtBanner.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteBanner"];
10 this.txtEmail.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteEmail"];
11 }
12 }

二、将修改后的内容写入Web.config

 1 private void btnSave_Click(object sender, System.EventArgs e)
2 {
3 string filename=Server.MapPath("web.config");
4 string KeyName;//键名称
5
6 XmlDocument xmldoc= new XmlDocument();
7 try
8 {
9 xmldoc.Load(filename);
10 }
11 catch
12 {
13 Response.Write("<script>alert('读文件时错误,请检查 Web.config 文件是否存在!')</script>");
14 return;
15 }
16
17 XmlNodeList DocdNodeNameArr=xmldoc.DocumentElement.ChildNodes;//文档节点名称数组
18 foreach(XmlElement DocXmlElement in DocdNodeNameArr)
19 {
20 if(DocXmlElement.Name.ToLower()=="appsettings")//找到名称为 appsettings 的节点
21 {
22 XmlNodeList KeyNameArr=DocXmlElement.ChildNodes;//子节点名称数组
23 if ( KeyNameArr.Count >0 )
24 {
25 foreach(XmlElement xmlElement in KeyNameArr)
26 {
27 KeyName=xmlElement.Attributes["key"].InnerXml;//键值
28 switch(KeyName)
29 {
30 case "Sitetitle":
31 xmlElement.Attributes["value"].value=this.txttitle.Text;
32 break;
33 case "SiteUrl":
34 xmlElement.Attributes["value"].value=this.txtUrl.Text;
35 break;
36 case "SiteLogo":
37 xmlElement.Attributes["value"].value=this.txtLogo.Text;
38 break;
39 case "SiteBanner":
40 xmlElement.Attributes["value"].value=this.txtBanner.Text;
41 break;
42 case "SiteEmail":
43 xmlElement.Attributes["value"].value=this.txtEmail.Text;
44 break;
45
46 }
47 }
48 }
49 }
50 }
51 try
52 {
53 xmldoc.Save(filename);
54 Response.Write("<script>alert('OK,信息已保存!')</script>");
55 }
56 catch
57 {
58 Response.Write("<script>alert('写文件时错误,请检查 Web.config 文件是否存在!')</script>");
59 return;
60 }
61 }





posted @ 2012-04-06 11:10  烧点饭  阅读(250)  评论(0编辑  收藏  举报