How to save configuration settings in C#

How to save settings really quick and easy in C # applications? I’m sure this question has been asked certainly by everyone once during his career as C# programmer. And did you know? The answer is quite simple. The easiest way to answer this question is to use the  AppSettings from ConfigurationManager class of the .Net-Framework.

The. Net Framework brings its own managers to save and load settings with it. The properties are stored in the common XML format. And so you can see that dealing with the AppSettings is really a no-brainer , I have written two small functions for saving, changing and reading preferences.

public string getAppSetting(string key)
{
    //Load the appsettings
    Configuration config = ConfigurationManager.OpenExeConfiguration(
                            System.Reflection.Assembly.GetExecutingAssembly().Location);
    //Return the value which matches the key
    return config.AppSettings.Settings[key].Value;
}

public void setAppSetting(string key, string value)
{
    //Load appsettings
    Configuration config = ConfigurationManager.OpenExeConfiguration(
                            System.Reflection.Assembly.GetExecutingAssembly().Location);
    //Check if key exists in the settings
    if (config.AppSettings.Settings[key] != null)
    {
        //If key exists, delete it
        config.AppSettings.Settings.Remove(key);
    }
    //Add new key-value pair
    config.AppSettings.Settings.Add(key, value);
    //Save the changed settings
    config.Save(ConfigurationSaveMode.Modified);
}

Looks pretty simple, right?

Best regards,
Raffi

0 Comments

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked