61

can anyone please help me how can I set/store values in the app.config file using c#, is it possible at all?

Rana
  • 5,912
  • 12
  • 58
  • 91
  • 12
    Did you google this at all? – Adriaan Stander Jan 21 '11 at 12:08
  • 1
    Could you be a bit more specific? What kind of value is it you wan't to store, and when? Generally it's not really recommended to store Application-wide values (like strings or ints) in the App config. – Mantisen Jan 21 '11 at 12:09
  • 3
    Asking a question that seems stupid by pros is all right, everybody starts with the beginning. However, not even taking a simpe google search is just lame. – Dercsár Jan 21 '11 at 12:25
  • 3
    I tried and also googled, tried few ways, but was getting no luck. that's why i asked so.. – Rana Jan 21 '11 at 12:53
  • Since you seem new to all this I want to add that the settings will need to be inside your .exe.config file. If you try to get or set from a dll (i.e. class library project or any other project except mstest projects from I have seen) it won't work. It WANTS your application exe file! You will need hackery otherwise. To be clear I am referring to using the ConfigurationManager for this. – Mike Cheel Jun 21 '16 at 19:03

11 Answers11

54

Try the following code:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add("YourKey", "YourValue");
    config.Save(ConfigurationSaveMode.Minimal);

It worked for me :-)

Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164
  • Thanks, the namespace is System.Configuration. So System.Configuration.Configuration config = .... – Rob Nov 17 '14 at 18:22
  • "Access to the path is denied" when i tried to install it. But when i try it in visual studio it works fine. Can you help me. – Reynan Nov 02 '16 at 11:15
33

On Framework 4.5 the AppSettings.Settings["key"] part of ConfigurationManager is read only so I had to first Remove the key then Add it again using the following:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

config.AppSettings.Settings.Remove("MySetting");
config.AppSettings.Settings.Add("MySetting", "some value");

config.Save(ConfigurationSaveMode.Modified);

Don't worry, you won't get an exception if you try to Remove a key that doesn't exist.

This post gives some good advice

D.G.
  • 337
  • 3
  • 4
30
private static string GetSetting(string key)
{
    return ConfigurationManager.AppSettings[key];
}

private static void SetSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save(ConfigurationSaveMode.Full, true);
    ConfigurationManager.RefreshSection("appSettings");
}
Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
fiaharon
  • 391
  • 3
  • 6
  • 1
    I had to add configuration.AppSettings.Settings.Add(value); before configuration.AppSettings.Settings[key].Value = value; to get this to work when the .config file was empty. – Ed Bayiates Mar 10 '16 at 23:23
  • 1
    When using `Settings.Add()`, if the entry doesn't exist, it will be added, if it already exists, the value will be added to the existing value(s) separated by a comma. E.g. after calling `Settings.Add("myKey", "test")` 4 times, your entry will become: `` – Stacked Jun 21 '16 at 18:23
  • 1
    ConfigurationManager.RefreshSection("appSettings"); was the key for me, if you don't do that, reading newly written values won't work. – Mr. Bungle Dec 02 '16 at 04:42
  • 1
    I would recommend using `ConfigurationManager.RefreshSection(configuration.AppSettings.SectionInformation.Name)` instead of the hard coded string. – Charles A. Aug 13 '20 at 16:32
14

If you are using App.Config to store values in <add Key="" Value="" /> or CustomSections section use ConfigurationManager class, else use XMLDocument class.

For example:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="server" value="192.168.0.1\xxx"/>
    <add key="database" value="DataXXX"/>
    <add key="username" value="userX"/>
    <add key="password" value="passX"/>
  </appSettings>
</configuration>

You could use the code posted on CodeProject

Ch3shire
  • 1,095
  • 2
  • 14
  • 39
AbrahamJP
  • 3,425
  • 7
  • 30
  • 39
11

As others mentioned, you can do this with ConfigurationManager.AppSettings.Settings. But: Using Settings[key] = value will not work if the key doesn't exist.
Using Settings.Add(key, value), if the key already exists, it will join the new value to its value(s) separated by a comma, something like <add key="myKey" value="value1, value2, value3" />

To avoid these unexpected results, you have to handle two scenario's

  • If entry with the given key exists? then update its value
  • if entry with the given key doesn't exist? then create new entry(key,value)

Code

public static void Set(string key, string value)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    var entry = config.AppSettings.Settings[key];
    if (entry == null)
        config.AppSettings.Settings.Add(key, value);
    else
        config.AppSettings.Settings[key].Value = value;

    config.Save(ConfigurationSaveMode.Modified);
}

For more info about the check entry == null, check this post.
Hope this will help someone.

Community
  • 1
  • 1
Stacked
  • 6,892
  • 7
  • 57
  • 73
7

For a .NET 4.0 console application, none of these worked for me. So I used the following below and it worked:

private static void UpdateSetting(string key, string value)
{
    Configuration configuration = ConfigurationManager.
        OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
    configuration.AppSettings.Settings[key].Value = value;
    configuration.Save();

    ConfigurationManager.RefreshSection("appSettings");
}
James John McGuire 'Jahmic'
  • 11,728
  • 11
  • 67
  • 78
5
string filePath = System.IO.Path.GetFullPath("settings.app.config");

var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
try
{
    // Open App.Config of executable
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

    // Add an Application Setting if not exist

        config.AppSettings.Settings.Add("key1", "value1");
        config.AppSettings.Settings.Add("key2", "value2");

    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);

    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}
catch (ConfigurationErrorsException ex)
{
    if (ex.BareMessage == "Root element is missing.")
    {
        File.Delete(filePath);
        return;
    }
    MessageBox.Show(ex.Message);
}
Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
marcus
  • 395
  • 5
  • 22
  • 2
    This response is uniquely helpful in that it shows how to open an arbitrary named config file and not just *.exe.config files; unlike other responses. – David Burg Mar 08 '19 at 19:25
4

Try the following:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            
config.AppSettings.Settings[key].Value = value;
config.Save();
ConfigurationManager.RefreshSection("appSettings");
Anish
  • 51
  • 1
3

Yes you can - see ConfigurationManager

The ConfigurationManager class includes members that enable you to perform the following tasks:

  • Read and write configuration files as a whole.

Learn to use the docs, they should be your first port-of call for a question like this.

m.edmondson
  • 30,382
  • 27
  • 123
  • 206
2
//if you want change
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings[key].Value = value;

//if you want add
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add("key", value);
2

I struggled with this for a while and finally figured it out on my own. I didn't find any help at the time, but wanted to share my approach. I have done this several times and used a different method than what is above. Not sure how robust it is, but it has worked for me.

Let's say you have a textbox named "txtName", a button named "btnSave" and you want to save the name so the next time you run your program the name you typed appears in that textbox.

  1. Go to Project>Properties>Settings and create a setting -
  • name = "Name"
  • type = "string"
  • scope = "user"
  • value you can leave blank.

Save your settings file.

  1. Go to your form where textbox and button exist. Double click your button and put this code in;
    //This tells your program to save the value you have to the properties file (app.config);
    //"Name" here is the name you used in your settings file above.
    Properties.Settings.Default.Name = txtName.txt;
    //This tells your program to make these settings permanent, otherwise they are only
    //saved for the current session
    Properties.Settings.Default.Save();
  1. Go to your form_load function and add this in there;
    //This tells your program to load the setting you saved above to the textbox
    txtName.txt = Properties.Settings.Default.Name;
  1. Debug your application and you should see the name you typed in.
  2. Check your application debug directory and you should see a .config file named after your program. Open that with a text editor and you will see your settings.

Notes -

  • "Name" refers to the actual name of the setting you created.
  • Your program will take care of creating the actual XML file, you don't have to worry about it.
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rekless
  • 139
  • 1
  • 5