Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add values to app.config and retrieve them

Tags:

c#

I need to insert key value pairs in app.Config as follows:

<configuration>  <appSettings>     <add key="Setting1" value="Value1" />     <add key="Setting2" value="Value2" />  </appSettings> </configuration> 

When I searched in google I got the following code snippet

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Add an Application Setting.  config.AppSettings.Settings.Add("ModificationDate",                DateTime.Now.ToLongTimeString() + " ");  // Save the changes in App.config file.  config.Save(ConfigurationSaveMode.Modified); 

The above code is not working as ConfigurationManager is not found in System.Configuration namespace I'm using .NET 2.0. How to add key-value pairs to app.Config programatically and retrieve them?

like image 380
softwarematter Avatar asked May 29 '09 11:05

softwarematter


People also ask

Where are app config files stored?

The application configuration file usually lives in the same directory as your application. For web applications, it is named Web. config. For non-web applications, it starts life with the name of App.

How do I access AppSettings in C#?

To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below.


2 Answers

Are you missing the reference to System.Configuration.dll? ConfigurationManager class lies there.

EDIT: The System.Configuration namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...

like image 162
Arjan Einbu Avatar answered Oct 14 '22 11:10

Arjan Einbu


This works:

public static void AddValue(string key, string value) {     Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);     config.AppSettings.Settings.Add(key, value);     config.Save(ConfigurationSaveMode.Minimal); } 
like image 24
Radicz Avatar answered Oct 14 '22 10:10

Radicz