有人能帮我理解为什么在向配置文件添加值后,我不能立即将其读入应用程序吗?我做了刷新,但这不起作用。见下文:
public void AddConfig(string key_value, string actual_value)
{
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
//If it exists, remove it first
config.AppSettings.Settings.Remove(key_value);
// Add an Application Setting.
config.AppSettings.Settings.Add(key_value, actual_value);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
string blah = ConfigurationManager.AppSettings[key_value];
MessageBox.Show(blah);
}
消息框将显示为空/空白。
如果我重新启动应用程序并在启动后运行另一个命令来读取键值,它将起作用。
有什么想法吗?
最佳答案
您遇到的问题很可能是由于在 Visual Studio 环境中运行应用程序所致。
直接从 Debug
或 Release
目录运行 .exe,RefreshSection()
方法将按预期工作。
如果你想在调试时看到改变的值,你需要使用 AppSettings.Settings
而不是 ConfigurationManager.AppSettings
:
string blah = config.AppSettings.Settings[key_value].Value
关于c# - 在重新启动应用程序之前无法读取 appSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16843971/