usingSystem;usingSystem.Configuration;namespaceconsoleapplication1{classProgram {Static voidMain (string[] args) {readallsettings (); Readsetting ("Setting1"); Readsetting ("Notvalid"); Addupdateappsettings ("newsetting","May 7,"); Addupdateappsettings ("Setting1","May 8,"); Readallsettings (); } Static voidreadallsettings () {Try { varAppSettings =configurationmanager.appsettings; if(Appsettings.count = =0) {Console.WriteLine ("AppSettings is empty."); } Else { foreach(varKeyinchAppsettings.allkeys) {Console.WriteLine ("Key: {0} Value: {1}", Key, Appsettings[key]); } } } Catch(configurationerrorsexception) {Console.WriteLine ("Error reading app settings"); } } Static voidReadsetting (stringkey) { Try { varAppSettings =configurationmanager.appsettings; stringresult = Appsettings[key]??"Not Found"; Console.WriteLine (result); } Catch(configurationerrorsexception) {Console.WriteLine ("Error reading app settings"); } } Static voidAddupdateappsettings (stringKeystringvalue) { Try { varConfigFile =configurationmanager.openexeconfiguration (Configurationuserlevel.none); varSettings =configFile.AppSettings.Settings; if(Settings[key] = =NULL) {settings. ADD (key, value); } Else{Settings[key]. Value=value; } configfile.save (configurationsavemode.modified); Configurationmanager.refreshsection (ConfigFile.AppSettings.SectionInformation.Name); } Catch(configurationerrorsexception) {Console.WriteLine ("Error writing app settings"); } } }}
The preceding example assumes that your project has an app. config file as shown below.
Xml
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <startup> <supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/> </startup> <appSettings> <add key=" Setting1 "value=" May 5, "/> <add key=" Setting2 "value=" 6 "/> </appSettings></configuration>
ConfigurationManager read-write appsettings key value pair