November 10, 2018

SImple Application Settings Manager

Heres a quick class to read and write settings to the application config file
// A Minimal class to read and write settings directly to the application 
// config file with NO write permission constraints. It does keep a separate
// copy of the config file for each user
// Only Key/Value style settings can be written, and string ones only at that but
// converting most simple types to and from a string is trivial.
public class SettingsManager : ISettingsManager
{
    public string ReadSetting(string key)
    {
        try
        {
            var appSettings = ConfigurationManager.AppSettings;
            var result = appSettings[key] ?? string.Empty;
            return result;
        }
        catch (ConfigurationErrorsException ex)
        {
            Trace.WriteLine("Configuration file exception : " + ex);
        }
        return string.Empty;
    }

    public void WriteSetting(string key, string value)
    {
        try
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;
            if (settings.Count == 0 | settings[key] == null)
            {
                settings.Add(key, value);
            }
            else
            {
                settings[key].Value = value;
            }
            configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(
                configFile.AppSettings.SectionInformation.Name);
        }
        catch (ConfigurationErrorsException ex)
        {
            Trace.WriteLine("Configuration file exception : "+ ex);
        }
    }

No comments: