修改app.config的值

本文内容:利用Configuration类修改app.config文件。

以下用代码说明:

在References中,添加System.configuration

app.config

1 <?xml version="1.0" encoding="utf-8"?>
2 <configuration>
3 <appSettings>
4 <add key="Debug" value="1"/>
5 </appSettings>
6 </configuration>

Main.cs

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Configuration;
7 namespace y.UpdateAppconfigExample
8 {
9 class Program
10 {
11 staticvoid Main(string[] args)
12 {
13 Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
14 configuration.AppSettings.Settings["Debug"].Value ="0";
15 configuration.Save(ConfigurationSaveMode.Modified);
16 }
17
18 }
19 }

另外通过xml的方式更改。方法代码如下:

View Code
 1 void UpdateAppconfig(string appconfigPath,string appKey, string appValue)
2 {
3 XmlDocument xDoc = new XmlDocument();
4 xDoc.Load(appconfigPath);
5 XmlNode xNode;
6 XmlElement xElem1;
7 XmlElement xElem2;
8 xNode = xDoc.SelectSingleNode("//appSettings");
9 xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
10 if (xElem1 != null)
11 {
12 xElem1.SetAttribute("value", appValue);
13 }
14 else
15 {
16 xElem2 = xDoc.CreateElement("add");
17 xElem2.SetAttribute("key", appKey);
18 xElem2.SetAttribute("value", appValue);
19 xNode.AppendChild(xElem2);
20 }
21 xDoc.Save(appconfigPath);
22 }

 

参考文献:

http://msdn.microsoft.com/zh-cn/library/6zwf9645(v=VS.90).aspx

http://www.cnblogs.com/sql4me/archive/2009/04/24/1442845.html

 

posted @ 2011-08-24 10:52  走过留痕  阅读(710)  评论(0编辑  收藏  举报