我写了一个小实用程序,允许我为另一个应用程序的App.config文件更改一个简单的AppSetting,然后保存更改:
//save a backup copy first.
var cfg = ConfigurationManager.OpenExeConfiguration(pathToExeFile);
cfg.SaveAs(cfg.FilePath + "." + DateTime.Now.ToFileTime() + ".bak");
//reopen the original config again and update it.
cfg = ConfigurationManager.OpenExeConfiguration(pathToExeFile);
var setting = cfg.AppSettings.Settings[keyName];
setting.Value = newValue;
//save the changed configuration.
cfg.Save(ConfigurationSaveMode.Full);
Run Code Online (Sandbox Code Playgroud)
这种效果很好,除了一个副作用.新保存的.config文件丢失所有原始XML注释,但仅在AppSettings区域内.是否可以从原始配置文件AppSettings区域保留XML注释?
c# xml configurationmanager configuration-files xml-comments