Csharp/C#教程:在运行时更改appconfig分享


在运行时更改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文件夹中的配置文件,否则不会看到对配置的任何更改。

上述就是C#学习教程:在运行时更改appconfig分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/984622.html

(0)
上一篇 2021年12月20日
下一篇 2021年12月20日

精彩推荐