Modify custom app.config config section and save it

≯℡__Kan透↙ 提交于 2019-12-05 18:54:41

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

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

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