编程修改读写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(); 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 C# 中,可以使用 `ConfigurationManager` 类来读写 `App.config` 文件。 首先需要在项目中添加 `System.Configuration` 引用。然后可以使用以下代码来访问 `App.config` 文件中的配置项: ```csharp using System.Configuration; // 读取 App.config 中的配置项 string value = ConfigurationManager.AppSettings["key"]; // 写入 App.config 中的配置项 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["key"].Value = "value"; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); ``` 其中,`AppSettings` 是 `App.config` 文件中的一个节点,保存了键值对形式的配置项。可以通过 `ConfigurationManager.AppSettings` 属性来获取该节点下的所有配置项,也可以使用 `Configuration.AppSettings.Settings` 属性来获取指定的配置项。 对于写入配置项,需要先使用 `ConfigurationManager.OpenExeConfiguration` 方法打开 `App.config` 文件,并且指定配置文件的用户级别。然后通过 `Configuration.AppSettings.Settings` 属性来设置指定的配置项的值,最后调用 `Configuration.Save` 方法来保存修改,并调用 `ConfigurationManager.RefreshSection` 方法来刷新配置项。 ### 回答2: C 的英文单词是 "cat",意思是猫。猫是一种可爱的动物,常见于全球各地的家庭和农场。猫是人类历史上最早被驯养的动物之一。它们有着柔软的毛发、敏锐的感觉和独特的行为习惯。猫咪通常喜欢独处,但也能与人建立深厚的关系。 猫的行为习惯独特而有趣。它们喜欢用力蹭头,以标记自己的领地。猫会通过抓挠家具或其他表面来磨尖自己的爪子。猫还会用尾巴来表达情绪,例如当它们高兴时会竖起尾巴。猫咪对捕捉小动物和玩具也很有兴趣,这是它们独特的猎食本能。 猫的品种繁多,每个品种都有不同的外貌和特点。比如波斯猫有长而柔软的毛发,而暹罗猫则有蓝色的眼睛和卷曲的尾巴。无论是哪种品种,猫的身体都非常灵活,具有非凡的跳跃能力和敏锐的听力。 猫有很多好处,它们是家庭中的好伙伴。与猫咪玩耍可以减轻压力和焦虑,同时增加幸福感。猫也可以成为一个好的捕鼠员,它们可以帮助控制室内的老鼠和其他害虫。猫还可以带来快乐和乐趣,通过观察它们的行为和与它们互动的方式。 总之,猫是被驯养和喜爱的动物,它们在人类文化中扮演着重要的角色。无论是作为宠物还是环境中的猎手,猫都是我们生活中不可或缺的一部分。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值