更新app.config之appSettings(不保留註解)
-
執行程式
class Program { static void Main(string[] args) { // 寫入config序號 UpdateSetting("TestSerial", "02"); } /// <summary> /// 更新App.Config 中AppSetting /// </summary> /// <param name="key">AppSetting Name</param> /// <param name="updateValue">AppSetting Value</param> private static void UpdateSetting(string key, string updateValue) { Configuration configuration = ConfigurationManager.OpenExeConfiguration( Assembly.GetExecutingAssembly().Location); configuration.AppSettings.Settings[key].Value = updateValue; configuration.Save(); } }
更新app.config之appSettings(保留註解)
-
執行程式
class Program { static void Main(string[] args) { // 寫入config序號 SaveSettingByXDocument("TestSerial", "02"); } /// <summary> /// 新增/更新App.Config 中AppSetting /// </summary> /// <param name="key">AppSetting Name</param> /// <param name="updateValue">AppSetting Value</param> private static void SaveSettingByXDocument(string key, string value) { Configuration configuration = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); var configPath = configuration.AppSettings.ElementInformation.Source; // 讀取config檔案 XDocument document = XDocument.Load(configPath); if (document?.Root == null) { return; } // 取得appSettings節點 XContainer appSettings = document.Element("configuration").Element("appSettings"); // 取得指定key的節點 XElement appSetting = appSettings.Elements("add").FirstOrDefault(x => x.Attribute("key").Value == key); if (appSetting != null) { appSetting.Attribute("value").Value = value; document.Save(configPath); } else { // 新增config設定 appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value))); document.Save(configPath); } } }
如有錯誤或建議,歡迎留言指教,謝謝!!
(相關內容如有侵犯隱私或著作權,請協助通知刪除,感謝)