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



我正在开发带有.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");
    }
}

您应该使用configurationsection类。本教程可以帮助:https://msdn.microsoft.com/en-us/library/2tw134k3.aspx

最新更新