C#配置文件App.config

在开发Web项目的时候,会有一个配置文件Web.config,用来存放一些全局的变量,如连接数据库用的字符串。相应的,在开发
winform程序时,也有一个配置文件,它就是App.config,这个文件的作用与Web.config大致相同,也可以用来存放程序所用的全局
变量及Value值。
1、新建app.config
可以这样添加app.config文件:在解决方案资源管理器中要添加app.config文件的项目名字上右键,选择->添加->新建项->应用程序
配置文件,直接用默认的名字就可以了。

2、使用app.config
 来看一个app.config文件的例子:

<configuration>
 <appSettings>
  <add key="ConnectionString" value="Data Source=BAI;Initial Catalog=GASSYS;Integrated Security=True;"/>
 </appSettings>
</configuration> 

可以看出,app.config和web.config一样,嗯,它也是一个XML文件。那怎么对这个文件中的元素进行读取操作呢?很简单,
来看代码:

string sqlConnectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(); 


3、修改app.config
这样就可以把app.config文件中ImgPath这个元素的Value值读取出来了。那怎么改写元素的值呢?在对app.config文件的元
素Value值进行修改操作时,只能把app.config文件当作一个普通的XML文件来对待,利用System.Xml.XmlDocument类把这个
app.config文件读到内存中,并通过System.Xml.XmlNode类找到appSettings节点,通过System.Xml.XmlElement类找到节点下的某个
元素,利用SetAttribute方法来修改这个元素的值后,最后再将app.config文件保存到原的目录中,这样,才算完成了对一个元素
Value值的修改操作。下面这个方法可完成对app.config文件appSettings节点下任意一个元素进行修改,当然,你也可能修改这个方
法,达到修改任意节点,任意元素的Value值。

 1  public static void SetValue(string AppKey, string AppValue)
 2         {
 3             System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
 4             xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
 5 
 6             System.Xml.XmlNode xNode;
 7             System.Xml.XmlElement xElem1;
 8             System.Xml.XmlElement xElem2;
 9             xNode = xDoc.SelectSingleNode("//appSettings");
10 
11             xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
12             if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
13             else
14             {
15                 xElem2 = xDoc.CreateElement("add");
16                 xElem2.SetAttribute("key", AppKey);
17                 xElem2.SetAttribute("value", AppValue);
18                 xNode.AppendChild(xElem2);
19             }
20             xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
21 }
原文地址:https://www.cnblogs.com/baiqjh/p/2695289.html