C # access the configuration file in the program
Zookeeper
C # access the configuration file in the program
In C # programming, the configuration file is sometimes used. How can I obtain or modify the relevant data in the configuration file in the program? The following uses a simple C # console program.
Create a C # console program and open solution resource manager, for example:
We can see that there is no configuration file in it. Next we will use the. net version to call it out. Select a project, right-click, and select Properties.
The configuration file is displayed. Add configuration information as follows:
Now let's add code to access this information.
////// Obtain the value based on the specified key in the configuration information. //////The specified key.///
Public static string GetConfigurationValue (string key) {return ConfigurationManager. deleetask[ key];}
////// Modify the value of the specified key in the configuration information. /////////Public static void SetConfigurationValue (string key, string value) {Configuration config = ConfigurationManager. openExeConfiguration (ConfigurationUserLevel. none); config. appSettings. settings [key]. value = value; config. save (ConfigurationSaveMode. modified); System. configuration. configurationManager. refreshSection ("receivettings ");}
After adding the code, you will find that the program reports an error. In this case, we should add a dll reference and add it to the file.
using System.Configuration;
Add code to the Main function
Static void Main (string [] args) {Console. writeLine (GetConfigurationValue ("id"); Console. writeLine (GetConfigurationValue ("sex"); Console. writeLine (GetConfigurationValue ("age"); SetConfigurationValue ("id", "007"); SetConfigurationValue ("sex", "female"); SetConfigurationValue ("age ", "26"); Console. writeLine (); Console. writeLine (GetConfigurationValue ("id"); Console. writeLine (GetConfigurationValue ("sex"); Console. writeLine (GetConfigurationValue ("age "));}
The running result is as follows: