2012-09-11 62 views
1

我想改變App.Config文件appsettings鍵值,一切工作正常,同時更改鍵值所有評論都刪除配置文件(我也想評論),任何人都可以幫助我有什麼錯我的代碼配置文件註釋被刪除,同時改變appsettings密鑰

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ConfigFilepath, 
       ConfigurationUserLevel.None); 
      config.AppSettings.Settings["IPAddress"].Value = "10.10.2.3"; 

      config.Save(ConfigurationSaveMode.Full); 
+3

可能重複[ConfigurationManager中可以保留在保存XML評論()?](http://stackoverflow.com/questions/1954358/can-configurationmanager-retain-xml-comments-on-save) – hybrid2102

回答

-3

在電話結束後,保存

ConfigurationManager.RefreshSection("appSettings"); 
+0

感謝爲您的答覆,實際上我試圖從另一個exe文件更改一個應用程序app.config文件,我不能使用「OpenExeConfiguration」。 – user1120572

+0

我很高興幫助你user1120571,最後調用ConfigurationManager.RefreshSection(「appSettings」); –

+1

謝謝Aghilas,在調用引用後,所有評論都在appsettings部分中刪除。 – user1120572

3

這是我如何解決了這個問題。就我而言,appSettings部分存儲在與web.config不同的文件中(使用configSource屬性)。

public static void SaveAppSetting(string key, string value) 
{ 
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 
    SaveUsingXDocument(key, value, config.AppSettings.ElementInformation.Source); 
} 

/// <summary> 
/// Saves the using an XDocument instead of ConfigSecion. 
/// </summary> 
/// <remarks> 
/// The built-in <see cref="T:System.Configuration.Configuration"></see> class removes all XML comments when modifying the config file. 
/// </remarks> 
private static void SaveUsingXDocument(string key, string value, string fileName) 
{ 
    XDocument document = XDocument.Load(fileName); 
    if (document.Root == null) 
    { 
     return; 
    } 
    XElement appSetting = document.Root.Elements("add").FirstOrDefault(x => x.Attribute("key").Value == key); 
    if (appSetting != null) 
    { 
     appSetting.Attribute("value").Value = value; 
     document.Save(fileName); 
    } 
}