1. 程式人生 > >C# 動態獲取、修改、更新配置檔案 實現思路

C# 動態獲取、修改、更新配置檔案 實現思路

       1、新增System.Configuration.dll引用;程式中新增using System.Configuration;

       讀取資料:(tbHost為文字控制元件)

tbHost.Text = ConfigurationManager.AppSettings["host"].ToString();

       2、修改、更新資料

private void btnOk_Click(object sender, EventArgs e)
        {
            if (tbHost.Text.Trim().Equals("") || tbUserid.Text.Trim().Equals("")) return;

            // 修改並更新配置檔案
            UpdateConfig("host", tbHost.Text.Trim());
            UpdateConfig("userid", tbUserid.Text.Trim());
        }

        private void UpdateConfig(string key,string value)
        {
            // 通過Xml方式(需using System.xml;)
            //XmlDocument doc = new XmlDocument();
            //doc.Load(Application.ExecutablePath + ".config");
            //XmlNode node = doc.SelectSingleNode(@"//add[@key='" + key + "']"); // 定位到add節點
            //XmlElement element = (XmlElement)node;
            //element.SetAttribute("value", value); // 賦值
            //doc.Save(Application.ExecutablePath + ".config");
            //ConfigurationManager.RefreshSection("appSetting"); // 重新整理節點

            // 利用Configuration
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings[key].Value = value;
            config.Save(ConfigurationSaveMode.Full);
            ConfigurationManager.RefreshSection("appSettings");
        }
       說明:經常遇到的問題是修改資料後配置檔案未能立即生效,再次讀取時依然是修改前的資料。參考上述程式碼時,如果還遇到這個問題,可嘗試把“Xml方式”(即UpdateConfig()中註釋部分取消註釋)和Congiguration方式一起使用。