修改app.config的值

來源:互聯網
上載者:User

本文內容:利用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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.