c# - 在重新启动应用程序之前无法读取 appSettings

标签 c#

有人能帮我理解为什么在向配置文件添加值后,我不能立即将其读入应用程序吗?我做了刷新,但这不起作用。见下文:

    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 环境中运行应用程序所致。

直接从 DebugRelease 目录运行 .exe,RefreshSection() 方法将按预期工作。

如果你想在调试时看到改变的值,你需要使用 AppSettings.Settings 而不是 ConfigurationManager.AppSettings:

string blah = config.AppSettings.Settings[key_value].Value

关于c# - 在重新启动应用程序之前无法读取 appSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16843971/

相关文章:

c# - 打开数据连接

c# - 如何在 C# 中正确处理空白、null 或空行

c# - 如何从/bin 目录中加载所有程序集

c# - Entity Framework 复合主键-如何获取列的顺序

c# - 如何从日期选择器后端检索格式化版本的日期

c# - 如何使用.net更改word文档的字体大小

c# - 将 BindingList 绑定(bind)到 ListBox 时遇到问题

c# - Datagridview:如何从列表中获取 "typeconvert"属性

c# - 查找字符串中出现次数最多的字符?

javascript - 如何在自定义控件TFS 2017中获取/设置WI字段值