Very often it is required to add custom tags or key in app.config or in web.config. Here is a simple way to add key in <appSettings> and then access it.
Find section <appSettings> or <appSettings/> in .config file and add your required keys and values, the following example is same for both .config files. here we go
An appSettings element in the root Web.config / App.config file that looks like the following:
<appSettings>
<add key=“myKeyName” value=“my custom setting value“/>
appSettings>
The <appSettings> element is a direct child of the <configuration> element and a peer of the system.web element.
Values read from the appSettings element of the .config file are always of type String. If the specified key does not exist in the .config file, no error occurs. Instead, an empty string is returned
C# Code:
using System.Collections.Specialized; using System.Configuration; string strKeysAndValues = ""; // get all keys and values in AppSettings element NameValueCollection sAll = ConfigurationManager.AppSettings; foreach (string s in sAll.AllKeys) { strKeysAndValues += "Key" + s + " value:"+ sAll.Get(s)+" "; } //OR string strKeysAndValues= ConfigurationSettings.AppSettings["myKeyName"].ToString();
Leave a Reply