c# - 修改自定义 app.config 配置部分并保存

标签 c# config configuration-management

我正在使用 .NET Framework 4.6.1 开发 C# WPF MVVM 应用程序,我在 App.config 中有一个自定义部分:

<configuration>
    <configSections>
        <section name="SpeedSection" type="System.Configuration.NameValueSectionHandler" />
    </configSections>
    <SpeedSection>
        <add key="PrinterSpeed" value="150" />
        <add key="CameraSpeed" value="150" />
    </SpeedSection>
</configuration>

我想从我的应用中修改 PrinterSpeedCameraSpeed。我试过这段代码:

static void AddUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

但它不起作用,因为我没有修改 AppSettings 部分。

如何修改这些值?

最佳答案

System.Configuration.NameValueSectionHandler 很难使用。您可以将其替换为 System.Configuration.AppSettingsSection 而无需触及任何其他内容:

<configuration>
    <configSections>
        <section name="SpeedSection" type="System.Configuration.AppSettingsSection" />
    </configSections>
    <SpeedSection>
        <add key="PrinterSpeed" value="150" />
        <add key="CameraSpeed" value="150" />
    </SpeedSection>
</configuration>

然后改变你的方法如下:

static void AddUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = ((AppSettingsSection) configFile.GetSection("SpeedSection")).Settings;                                
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

关于c# - 修改自定义 app.config 配置部分并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40737395/

相关文章:

c# - 在不重新查询数据库的情况下,在另一个 LINQ 查询中重用 LINQ 查询结果

command-line - Vagrant 提供实时输出

Git - 删除和排除配置文件

c# - .net 接口(interface)与泛型方法,实现中的错误

C# HMAC 到 Java

c# - MouseEnter WPF 上的发光效果

javascript - 这一行 webpack html loader 语法是什么意思?

Git checkout 因分离的工作树而失败

ruby-on-rails - 为什么在本地强制使用 https?

Linux系统和服务信息