C#winform 程式,代碼修改app.config

來源:互聯網
上載者:User
用下面的方法可以操作應用程式檔案夾下的設定檔:

在winform中使用程式讀取和修改App.config裡面的appSettings當中的Value值

這裡我寫成了兩個方法,以供大家參考!
一,命名空間
using System;
using System.Configuration;
using System.Xml;
二,方法
//讀取Value值
public static string GetConfigString(string key)
{
//
// TODO: 在此處添加建構函式邏輯
//
return ConfigurationSettings.AppSettings[key];
}
//寫操作
public static void SetValue(string AppKey,string AppValue)
{
XmlDocument xDoc = new XmlDocument();
//擷取可執行檔的路徑和名稱
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");

xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if ( xElem1 != null ) xElem1.SetAttribute("value",AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key",AppKey);
xElem2.SetAttribute("value",AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");

}

 

當Properties.Settings變數的範圍"scope"設定為使用者"user"時,通過上述方式讀寫操作並不是操作 了"test.exe.config"檔案,實際操作的檔案儲存在"C:\Documents and Settings\Administrator\Local Settings\Application Data\"路徑下面(註:Administrator是目前使用者檔案夾),檔案名稱字叫"user.config"。點擊工程Properties頁面 中"設定"選項卡的"同步"按鈕會提示這個路徑。 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.