Modify custom app.config config section and save it

两盒软妹~` 提交于 2020-01-02 06:18:27

问题


I'm developing a C# WPF MVVM application with .NET Framework 4.6.1 and I have a custom section in 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>

I want to modify PrinterSpeed and CameraSpeed from my app. I have tried this code:

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");
    }
}

But it doesn't work because I'm not modifying AppSettings section.

How can I modify those values?


回答1:


System.Configuration.NameValueSectionHandler is hard to work with. You can replace it with System.Configuration.AppSettingsSection without touching anything else:

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

And then change your method as follows:

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");
    }
}



回答2:


You should use ConfigurationSection class. This tutorial could help: https://msdn.microsoft.com/en-us/library/2tw134k3.aspx



来源:https://stackoverflow.com/questions/40737395/modify-custom-app-config-config-section-and-save-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!