在运行时更改appconfig

我试图使用以下代码在运行时更新appconfig文件。 我没有收到错误,但它没有更新我的配置文件。

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string oldValue = config.AppSettings.Settings["Username"].Value; config.AppSettings.Settings["Username"].Value = "NewValue"; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); 

添加config.AppSettings.SectionInformation.ForceSave = true; 会做的伎俩。 然后,您应该在调试时查看YourProject.vshost.exe.config ,Justin说。 修改保存在那里。

只要您具有对app.config文件的写入权限,就可以使用以下内容。

 // To Save System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["Username"].Value = "NewValue"; config.AppSettings.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); // To Refresh ConfigurationManager.RefreshSection("appSettings"); System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

您无法更新配置。 您必须将其删除,然后重新添加。 这对我有用,包括在通过Visual Studio进行调试时:

 config.AppSettings.Settings.Remove("Username"); config.AppSettings.Settings.Add("Username", "NewValue"); config.Save(ConfigurationSaveMode.Modified); 

当我需要更新配置时,我总是要使用:

 config.AppSettings.SectionInformation.ForceSave = true; //Save config //Refresh Config section 

否则它不会为我更新配置文件。

另外,你在Visual Studio中运行它吗? 如果从Visual Studio进行调试,它会在bin文件夹中创建副本,因此在实际项目中,除非您查看bin \ debug文件夹中的配置文件,否则不会看到对配置的任何更改。