kyle_13
kyle_13

Reputation: 1233

How to update the value of an existing config key in .NET?

Take the example...

<add key="IDs" value="001;789;567"/>

How do you update (append to) the value only of an existing key in the App.config programatically?

<add key="IDs" value="001;789;567;444"/>

My code currently has the below to add new keys, but I don't know how to update keys.

System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Add(appKey, appKeyValue);

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

Upvotes: 4

Views: 461

Answers (1)

Darren
Darren

Reputation: 70766

You can access it via the Settings key or indexer.

Configuration config = ConfigurationManager.OpenExeConfiguration("YourConfigFilePath");
config.AppSettings.Settings["IDS"].Value = "001;789;567;444";  // Update the value (You could also use your appKey variable rather than the string literal.

config.Save();

As an additional note it may be easier to import the System.Configuration namespace rather than using the System.Configuration alias each time.

Upvotes: 3

Related Questions