45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 电脑教程 > 阅读资讯:编程修改读写web.config文件的方法

编程修改读写web.config文件的方法

2016-09-02 07:31:32 来源:www.45fan.com 【

编程修改读写web.config文件的方法

http://blog.csdn.net/deepbluekk/archive/2006/08/16/1067739.aspx
http://blog.csdn.net/intao/archive/2006/04/16/665654.aspx


问题简述:

在Web开发中,对web.cofig进行配置是非技术人员无法胜任的工作,但是常常需要由客户自己来进行简单配置的时候,需要提供一个有效的工具来指导客户完成这项操作,并且防止无效或错误的更改。

解决方案:

首先,必须了解对系统的配置主要包括machine.config和web.config两个部分,这两个文件本质上是Xml文件,包含了ASP.NET的所有配置信息。因此,对系统的配置,实际上是对Xml文件的操作,因此,我们可以采取对Xml文件的读写操作,来实现快速配置的思路。在此我们主要以web.config为例来说明,Web.config中的各个数据项表示的内容,不是探讨的重点,具体内容可以参考Msdn的说明。

实现的核心代码为:


private void btnOK_Click(object sender, System.EventArgs e)
{
//定义变量
string strLocation=txtLocation.Text;
string strProvider=txtProvider.Text;
string strMode=txtMode.Text;
string strUser=txtUser.Text;
string strDataSource=txtDataSource.Text;
string strPwd=txtPwd.Text;

string semicolon=";";

//操作XML节点
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("myXML.xml");
XmlNode xNode=xmlDoc.SelectSingleNode("//appSettings/add[@key='oledbConnection1.ConnectionString']");
if(xNode!=null)
{
xNode.Attributes["value"].Value="Location="+strLocation+semicolon+"Provider="+strProvider+semicolon+
"Mode="+strMode+semicolon+"User ID="+strUser+semicolon+"Data Source="+strDataSource+semicolon+
"Password="+strPwd;
}
xmlDoc.Save("myXML.xml");

MessageBox.Show("设置成功!");
}



代码中,我们以myXML.xml为例,可以代表其他任何XML的修改。

这些只是简单的一个数据项的操作,更进一步的操作需要继续完善。

在下面的操作界面上,非技术人员就可以很方便的修改其中的各项信息。

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=762995

1 using System;
2 using System.Collections;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Web;
7 using System.Web.SessionState;
8 using System.Web.UI;
9 using System.Web.UI.WebControls;
10 using System.Web.UI.HtmlControls;
11 using System.Xml ;
12
13
14 namespace WebApplication1
15 {
16 /// <summary>
17 /// Summary description for WebForm1.
18 /// </summary>
19 public class WebForm1 : System.Web.UI.Page
20 {
21 protected System.Web.UI.WebControls.TextBox TextBox1;
22 protected System.Web.UI.WebControls.DropDownList DropDownList1;
23 protected System.Web.UI.WebControls.Button Button1;
24
25 public WebForm1()
26 {
27 Page.Init += new System.EventHandler(Page_Init);
28 }
29
30 private void Page_Load(object sender, System.EventArgs e)
31 {
32 if(!Page.IsPostBack)
33 {
34 //打开某文件(假设WEB。CONFIG在根目录中)
35 string filename=Server.MapPath("/") + @"/web.config";
36 XmlDocument xmldoc= new XmlDocument();
37 xmldoc.Load(filename);
38
39 XmlNodeList topM=xmldoc.DocumentElement.ChildNodes;
40 foreach(XmlElement element in topM)
41 {
42 if(element.Name.ToLower()=="appsettings")
43 {
44 XmlNodeList _node=element.ChildNodes;
45 if ( _node.Count >0 )
46 {
47 DropDownList1.Items.Clear();
48 foreach(XmlElement el in _node)
49 {
50 DropDownList1.Items.Add(el.Attributes["key"].InnerXml);
51 }
52 }
53 }
54 }
55 }
56 }
57
58 private void Page_Init(object sender, EventArgs e)
59 {
60 InitializeComponent();
61 }
62
63 #region Web Form Designer generated code
64 /// <summary>
65 /// Required method for Designer support - do not modify
66 /// the contents of this method with the code editor.
67 /// </summary>
68 private void InitializeComponent()
69 {
70 this.Button1.Click += new System.EventHandler(this.Button1_Click);
71 this.Load += new System.EventHandler(this.Page_Load);
72
73 }
74 #endregion
75
76 private void Button1_Click(object sender, System.EventArgs e)
77 {
78 string filename=Server.MapPath("/") + @"/web.config";
79 XmlDocument xmldoc= new XmlDocument();
80 xmldoc.Load(filename);
81
82 XmlNodeList topM=xmldoc.DocumentElement.ChildNodes;
83 foreach(XmlElement element in topM)
84 {
85 if(element.Name.ToLower()=="appsettings")
86 {
87 XmlNodeList _node=element.ChildNodes;
88 if ( _node.Count >0 )
89 {
90 foreach(XmlElement el in _node)
91 {
92 if(el.Attributes["key"].InnerXml.ToLower()==this.DropDownList1.SelectedItem.Value.ToLower())
93 {
94 el.Attributes["value"].Value=this.TextBox1.Text;
95 }
96 }
97 }
98 }
99 }
100 xmldoc.Save(filename);
101 }
102 }


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


private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
//将Web.config中的相关值填入TextBox
this.txtTitle.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteTitle"];
this.txtUrl.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteUrl"];
this.txtLogo.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteLogo"];
this.txtBanner.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteBanner"];
this.txtEmail.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteEmail"];
}

}

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

private void btnSave_Click(object sender, System.EventArgs e)
{
string filename=Server.MapPath("web.config");
string KeyName;//键名称

XmlDocument xmldoc= new XmlDocument();
try
{
xmldoc.Load(filename);
}
catch
{
Response.Write("<script>alert('读文件时错误,请检查 Web.config 文件是否存在!')</script>");
return;
}

XmlNodeList DocdNodeNameArr=xmldoc.DocumentElement.ChildNodes;//文档节点名称数组
foreach(XmlElement DocXmlElement in DocdNodeNameArr)
{
if(DocXmlElement.Name.ToLower()=="appsettings")//找到名称为 appsettings 的节点
{
XmlNodeList KeyNameArr=DocXmlElement.ChildNodes;//子节点名称数组
if ( KeyNameArr.Count >0 )
{
foreach(XmlElement xmlElement in KeyNameArr)
{
KeyName=xmlElement.Attributes["key"].InnerXml;//键值
switch(KeyName)
{
case "SiteTitle":
xmlElement.Attributes["value"].Value=this.txtTitle.Text;
break;
case "SiteUrl":
xmlElement.Attributes["value"].Value=this.txtUrl.Text;
break;
case "SiteLogo":
xmlElement.Attributes["value"].Value=this.txtLogo.Text;
break;
case "SiteBanner":
xmlElement.Attributes["value"].Value=this.txtBanner.Text;
break;
case "SiteEmail":
xmlElement.Attributes["value"].Value=this.txtEmail.Text;
break;

}
}
}
}
}
try
{
xmldoc.Save(filename);
Response.Write("<script>alert('OK,信息已保存!')</script>");
}
catch
{
Response.Write("<script>alert('写文件时错误,请检查 Web.config 文件是否存在!')</script>");
return;
}

}

103 }
104
105


Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
conSection.ConnectionStrings["SQLConnectionString"].ConnectionString = "Data Source=192.168.0.41;Initial Catalog=Wahaha;Persist Security Info=True;User ID=apuser;Password=pass";
config.Save();

 

本文地址:http://www.45fan.com/dnjc/71141.html
Tags: 修改 读写 编程
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部