C # app. Config detailed

Source: Internet
Author: User
Tags connectionstrings

The application configuration file is a standard XML file, and XML tags and attributes are case-sensitive. It can be changed as needed, and developers can use the configuration file to change the settings without having to recompile the application.
The root node of the profile is the configuration file. We often visit appsettings, which is made up of. NET pre-defined configuration section. The schema of the configuration file that we often use is like the following form.
First of all, there is an impression that the following example will have a clearer understanding. The following "configuration section" can be understood as a node that configures an XML.
1.   add  app.config  files to the project: Right-click the project name, choose Add → add new item, and in the Add New Item dialog box that appears, select Add application configuration file, or if the project has not previously had a configuration file, The default file name is  app.config , click OK. The app.config  file that appears in Designer view is:<? xml version =  "1.0 " encoding =  "Utf-8   " ?>< configuration ></ configuration > after the project is compiled, the  bin/ debuge  file, two configuration files will appear   (  take this project as an example  ) &nbsp, one named "jxcmanagement.exe.config " and another named "  jxcmanagement.vshost.exe.config  ". The first file is the configuration file that the project is actually using, and the changes that are made in the program run are saved here, and the second file is the original code " app.config ", and the file is not changed while the program is running. 2.  connectionstrings  configuration section: Please note: If your  SQL  version is  2005 express  version, the default installation is  sql   The server instance name is LOCALHOST/SQLEXPRESS&NBSP, and you must change the " data source=localhost; " sentence in the following instance to " data source= localhost/sqlexpress;  ", do not add an overhead grid on either side of the equals sign. <!--  Database connection string  -->     < connectionStrings >          < clear />         < add name =  " conjxcbook  "               connectionstring =  "Data source=localhost;initial Catalog=jxcbook; User                                    id=sa;password=********   "              providername =   "system.data.sqlclient "  />     </ connectionstrings >3.  appSettings  configuration section:appsettings  configuration section for the entire program, if the configuration is for the current user, use the  userSettings  configuration section, The format is the same as the following configuration writing requirements. <!--  Invoicing management system initialization required parameters  -->     < appSettings >          &LT;&NBSP;CLEAR&Nbsp;/>         < add key =  "username " value =  ""  />         < add key =   "password " value =  ""  />         <  add key =  "department " value =  ""  />          < add key =  "returnvalue " value =  ""  />          < add key =  "pwdpattern " value =   " />         < add key = " userpattern  "value = "  /></ appSettings >4.  Read and update   App. Config for app.config  files read and write, referring to the network article:http://www.codeproject.com/csharp/  systemconfiguration.asp titled " Read/write App. Config File with. NET 2.0 "article. Note: To access the App. Config file using the following code, you must add a reference to System.Configuration.dll in the project, in addition to the reference system.configuration. 4.1 Read connectionstrings configuration section/// <summary>///  returns a data connection string based on the connection string name ConnectionName/// </summary >/// <param name= "ConnectionName" ></param>/// <returns></returns>private  static string getconnectionstringsconfig (String connectionname) {string  ConnectionString =        configurationmanager . Connectionstrings[connectionname]. Connectionstring.tostring ();     console . WriteLine (connectionString);     return connectionstring;} 4.2 Update connectionstrings configuration section/// <summary>///  Update connection string/// </summary>/// <param Name= "NewName" >  connection string name  </param>/// <param name= "newconstring" >  connection string contents  </param>/// <param name= "Newprovidername" >  Data provider name &NBSP;&LT;/PARam>private static void updateconnectionstringsconfig (string newname,     string newconstring,    string newprovidername) {     Bool ismodified = false ;    //  Records If the connection string already exists     //   If the connection string you want to change already exists     if  (configurationmanager . Connectionstrings[newname]!= null )     {        IsModified = true ;   }    //  Create a new connection string instance      connectionstringsettings mysettings =        new  connectionstringsettings  (NewName, newconstring, Newprovidername);    //  Open the executable configuration file *.exe.config    configuration config =         configurationmanager . OpenexeconfiguratiOn (configurationuserlevel . None);    //  If the connection string already exists, first delete it     if  (ismodified)      {        CONFIG. ConnectionStrings.ConnectionStrings.Remove (newName);   }    //  Add a new connection string to the configuration file .    config. CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (mysettings);    //  Save changes to the configuration file      CONFIG. Save (configurationsavemode . Modified);    //  force the connectionstrings configuration section of the configuration file to be loaded again      configurationmanager . Refreshsection ("ConnectionStrings"  );} 4.3 Read appstrings configuration section/// <summary>///  returns the value item of the appsettings configuration section in the *.exe.config file/// </summary >/// <param name= "Strkey" ></param>/// <returns></returns>private  Static string getappconfig (String strkey) {    foreach  (string key  in configurationmanager . AppSettings)     {        if  (key = = strkey)          {             return configurationmanager . appsettings[strkey];       }   }     return null ;} 4.4 Update connectionstrings configuration section/// <summary>///  add a pair of keys, value pairs/// </in the *.exe.config file appsettings configuration section Summary>/// <param name= "NewKey" ></param>/// <param name= "NewValue" ></param >private static void updateappconfig (String newkey, string newvalue) {     bool ismodified = false ;       foreach   (STRING&NBSP;KEY&NBSP;IN&NBSP;CONFIGURATIONMANAGER&NBSP;. AppSettings)     {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;IF&NBSP; (key==newkey)         {                ismodified = true ;       }    }     //Open App. Config of executable     Configuration config =        configurationmanager . Openexeconfiguration (configurationuserlevel . None);     //need to remove the old Settings object before you can replace IT&NBSP;&NBSP;&NBSP;&NB sp;if  (ismodified)     {        config. AppSettings.Settings.Remove (NewKey);   }       //Add an Application setting.    CONFIG. APPSETTINGS.SETTINGS.ADD (newkey,newvalue);       //Save The changes in app. Config file .    CONFIG. Save (Configurationsavemode . Modified);     //force a reload of a changed Section.    configurationmanager  . Refreshsection ("appSettings"  );

}

C # Read and write data in app. Config

Read the statement:

String str = configurationmanager.appsettings["Demokey"];

Write a statement:

Configuration CFA = configurationmanager.openexeconfiguration (Configurationuserlevel.none);
CfA. appsettings.settings["Demokey"]. Value = "Demovalue";
CfA. Save ();

Configuration file Content format: (app. config)

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<add key= "Demokey" value= "*"/>
</appSettings>
</configuration>

several key sections marked with red pens are required

system.configuration.configurationsettings.appsettings["Key"];

But now FrameWork2.0 has made it clear that this property is obsolete. It is proposed to replace ConfigurationManager

or WebConfigurationManager. And the AppSettings property is read-only and does not support modifying property values.

However, to invoke ConfigurationManager, you must first add a reference to the System.Configuration.dll assembly in the project.

(Right-click the project name in the Solution Manager and select Add Reference in the right-click menu to find it under. NET Tablepage.)
After adding a reference, you can use String str = configurationmanager.appsettings["Key" to get the corresponding value.

To update a configuration file:

Configuration CFA = ConfigurationManager. Openexeconfiguration (Configurationuserlevel.none); CFA.   APPSETTINGS.SETTINGS.ADD ("Key", "Name") | | CfA. appsettings.settings["Browsedir"]. Value = "name";

Wait a minute...
Last Call
CfA. Save ();
The current configuration file update was successful.

*************************************************************************************************************** **

Read-write configuration file app. Config
The configuration file is provided in. NET, which allows us to handle configuration information in an XML format. And. NET has already provided some functionality to access this file.

1. Read configuration information
The following is a description of the configuration file:

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<add key= "connenctionstring" value= "*"/>
<add key= "Tmppath" value= "C:\Temp"/>
</appSettings>
</configuration>

. NET provides a way to directly access the <appsettings> (note-case) element, where there are a number of child elements, the names of which are "add," and two attributes are "key" and "value", respectively. In general, we can write our own configuration information in this area, accessed in the following way:

String constring=system.configuration. configurationsettings.appsettings["Connenctionstring"]; after AppSettings is the value of the child element's key property, such as appsettings[" Connenctionstring "], we are to visit <add key=" connenctionstring "value=" * "/> This child element, its return value is" * ", that is, the Value property.

2. Setting Configuration information

If the configuration information is static, we can configure it manually, pay attention to the format. If the configuration information is dynamic, we need to write the program to implement. Without the ability to write configuration files in. NET, we can manipulate the configuration file in a way that operates an XML file. Here is an example of a write configuration file.

private void Saveconfig (string connenctionstring)
{
XmlDocument doc=new XmlDocument ();
Get the full path of the configuration file
String strfilename=appdomain.currentdomain.basedirectory.tostring () + "Code.exe.config";
Doc. LOAd (strFileName);
Find all elements with the name "add"
XmlNodeList Nodes=doc. getElementsByTagName ("add");
for (int i=0;i<nodes. count;i++)
{
Gets the key property of the current element
XmlAttribute Att=nodes[i]. attributes["Key"];
Determines whether the current element is a target element based on the first attribute of the element
if (Att. value== "ConnectionString")
{
Assign a value to the second attribute in the target element
Att=nodes[i]. attributes["value"];
Att. value=connenctionstring;
Break
}
}
Save the changes above
Doc. Save (strFileName);
} Read and modify the App. Config file
1.  Add the App. config file to the project: Right-click the project name, choose Add → add new item, and in the Add New Item dialog box that appears, select Add application configuration file, or if the project has not previously had a profile, the default file name is " App. Config, click OK. The app. config file that appears in Designer view is: <?xmlversion= "1.0" encoding= "Utf-8"  ?><configuration></ Configuration> after the project has been compiled, under the Bin\debuge file, there will be two configuration files (for this project, for example), one named "JxcManagement.EXE.config" and another named " JxcManagement.vshost.exe.config ". The first file is the configuration file that is actually used by the project, and the changes made in the program run are saved here, and the second file is the original code "app. Config" synchronization file, which does not change during program run. 2.  connectionstrings configuration section: NOTE: If your SQL version is 2005 Express, the SQL Server instance named Localhost\sqlexpress is installed by default and must be changed in the following instance " Data source=localhost; " The word "Data source=localhost\sqlexpress;", do not add an overhead grid on either side of the equals sign. <!--database connection string-->     <connectionStrings>          <clear />         <addname= "Conjxcbook"                connectionstring= "Data Source=localhost ; Initial Catalog=jxcbook; User &NBSP;&NBSP;&NBSP;&NBSP;&NBsp;                              id=sa;password=******** "               providername= "System.Data.SqlClient"  />      </connectionstrings>3. appsettings configuration section: AppSettings configuration section for the entire program configuration, if it is a configuration for the current user, Use the UserSettings configuration section in the same format as the following configuration writing requirements. <!--Invoicing Management system initialization required parameters-->     <appSettings>          <clear />         <addkey= "userName" value= ""  />         <addkey= "password" value= ""  />          <addkey= "Department" value= ""  />          <addkey= "returnvalue" value= ""  />         <addkey= "Pwdpattern" value= ""  />         <addkey = "Userpattern" value= ""  /></appsettings>4. Read and Update App. Config for reading and writing to the App. Config file, referring to the Network article:/http The www.codeproject.com/csharp/SystemConfiguration.asp is titled "Read/write App. config File with. NET 2.0". Note: To access the App. Config file using the following code, you must add a reference to System.Configuration.dll in the project, in addition to the reference system.configuration. 4.1 Read connectionstrings configuration section///<summary>///returns a data connection string based on the connection string name ConnectionName///</summary>///<param Name= "ConnectionName" ></param>///<returns></returns>private static string  Getconnectionstringsconfig (string connectionname) {string connectionstring =         configurationmanager.connectionstrings[connectionname]. Connectionstring.tostring ();     console.writeline (ConnectionString);     return connectionstring;} 4.2 Update connectionstrings configuration section///<summary>///update connection string///</summary>///<param name= "NewName" > Connection string name </param>///<param name= "Newconstring" > Connection string content </param>///<param name= "Newprovidername" > Data provider name </param>private static  Void updateconnectionstringsconfig (String newname,    string newconstring,     string newprovidername) {    bool ismodified = false;     //records whether the connection string already exists     //if the connection string you want to change already exists     if  ( Configurationmanager.connectionstrings[newname]!= null)     {         ismodified = true;   }    //Create a new connection string instance      connectionstringsettings mysettings =        new  Connectionstringsettings (NewName, newconstring, Newprovidername);    //  Open the executable configuration file *. Exe.config&nBsp;   configuration config =         Configurationmanager.openexeconfiguration (Configurationuserlevel.none);    //  If the connection string already exists, first delete it     if  (ismodified)     {         CONFIG. ConnectionStrings.ConnectionStrings.Remove (newName);   }    //  Add a new connection string to the configuration file .    config. CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (mysettings);    //  Save changes to the configuration file      CONFIG. Save (configurationsavemode.modified);    //  force the connectionstrings configuration section of the configuration file to be loaded again      configurationmanager.refreshsection ("ConnectionStrings");} 4.3 Read appstrings configuration section///<summary>///returns the value item of the appsettings configuration section in the *.exe.config file///</summary>///<param Name= "Strkey" ></param>///<returns></returns>private static string  GetappconfiG (String strkey) {    foreach  (string key in  configurationmanager.appsettings)     {        if  ( Key = = strkey)         {             return ConfigurationManager.AppSettings[strKey];        }   }    return null;} 4.4 Update connectionstrings configuration section///<summary>///add a pair of keys, value pairs///</summary>///< in the *.exe.config file appsettings configuration section param name= "NewKey" ></param>///<param name= "NewValue" ></param>private static void  updateappconfig (String newkey, string newvalue) {    bool  IsModified = false;       foreach  (string key in  configurationmanager.appsettings)     {       if (key==newkey)         {                ismodified = true;        }   }     //Open App. Config of executable     configuration config =         Configurationmanager.openexeconfiguration (configurationuserlevel.none);     //need to Remove the old Settings object before you can replace it    if  (ismodified)     {         CONFIG. AppSettings.Settings.Remove (NewKey);   }       //Add an Application setting.    CONFIG. APPSETTINGS.SETTINGS.ADD (newkey,newvalue);       //Save The changes in app. Config file .    CONFIG. Save (Configurationsavemode.modified);     //force a reload of a changed section.     Configurationmanager.refreshsection ("AppSettings");} Url:http://greatverve.cnblogs.com/archive/2011/07/18/app-config.html

C # app. Config detailed

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.