- First add the System.Configuration reference
- A using system.configuration must be in the class file;
- App. Config Add
- Add parameters to the App. config configuration file
Example:
In this app. config profile, I added 4 parameters, and the app. Config parameter is similar to Hashtable, which is a key/value pair
<?xml version="1.0"encoding="Utf-8"?><configuration> <appSettings> <add key="thedate"Value="2015-07-20 16:25"/> <add key="thename"Value="Alice"/> <add key="Thetype"Value="NBA"/> <add key="Theprice"Value="12500.00"/> </appSettings></configuration>
How do I access the parameter values in the app. config configuration file?
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Configuration;namespaceappconfigdemo{classProgram {Static voidMain (string[] args) { //determine if there is a key (not null) in the App. config configuration file if(ConfigurationManager.AppSettings.HasKeys ()) {//Loop through all the keys in the configuration file key foreach(stringSinchconfigurationmanager.appsettings) {Console.WriteLine (s); }} console.readkey (); } }}
The code for traversing key with a For loop is as follows:
static void Main (string [] args) { //
Determine if there is a key (non-null)
if
// Loop through all the keys in the configuration file key for (int i = 0 ; i < ConfigurationManager.AppSettings.Count; I++
method to access value via key:
Static voidMain (string[] args) { //determine if there is a key (not null) in the App. config configuration file if(ConfigurationManager.AppSettings.HasKeys ()) {//gets the value of the "Thedate" key foreach(stringSinchConfigurationManager.AppSettings.GetValues ("thedate") {Console.WriteLine (s); }} console.readkey (); }
What if you want to get the value collection for all keys?
Idea: All keys are traversed and stored in a container (for example, an array), and then a key match is used to find the value.
The code is as follows:
Static voidMain (string[] args) { //determine if there is a key (not null) in the App. config configuration file if(ConfigurationManager.AppSettings.HasKeys ()) {List<string> Thekeys =Newlist<string> ();//save a collection of keyslist<string> thevalues =Newlist<string> ();//save a collection of value//iterate through all the keys and add them into the Thekeys collection foreach(stringThekeyinchConfigurationManager.AppSettings.Keys) {thekeys.add (Thekey); } //iterates through all of the value according to key and adds the Thevalues collection for(inti =0; i < Thekeys.count; i++) { foreach(stringThevalueinchConfigurationManager.AppSettings.GetValues (Thekeys[i])) {Thevalues.add (thevalue); } } //VerifyConsole.WriteLine ("*************key*************"); foreach(stringSinchThekeys) {Console.WriteLine (s); } Console.WriteLine ("************value************"); foreach(varIteminchthevalues) {Console.WriteLine (item); }} console.readkey (); }
. NET how to get parameter values in the app. config configuration file