C # app. Config detailed

Source: Internet
Author: User

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 the app. Config file to the project: Right-click the project name, choose Add → add new item, in the Add New Item dialog box that appears, select Add Application profile, or if the project does not previously have 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 is 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: Please note: If your SQL version is 2005 Express Edition, the default installation of SQL Server instance named Localhost/sqlexpress, you must change the following instance in the "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 id=sa;password=******** "providername=" System.Data.SqlClient "/></connectionstrings>3. AppSettings configuration section: The appsettings configuration section is the configuration of the entire program, and 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 to read and write to the app. Config file, 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> Privatestaticstringgetconnectionstringsconfig (stringconnectionname) {stringconnectionstring = Configurationmanager.connectionstrings[connectionname]. Connectionstring.tostring (); Console.WriteLine (connectionString); returnconnectionstring;} 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 </param> Privatestaticvoidupdateconnectionstringsconfig (stringnewname,stringnewconstring,stringnewprovidername) { Boolismodified =false;//Records If the connection string already exists//if the connection string to be changed already exists if (Configurationmanager.connectionstrings[newname]!=null) { IsModified =true;} Create a new connection string instance Connectionstringsettingsmysettings =newconnectionstringsettings (NewName, newconstring, Newprovidername);//Open the executable configuration file *.exe.configconfigurationconfig =configurationmanager.openexeconfiguration ( Configurationuserlevel.none);//If the connection string already exists, first remove it if (ismodified) {config. ConnectionStrings.ConnectionStrings.Remove (newName);} Adds a new connection string to the configuration file. Config.ConnectionStrings.ConnectionStrings.Add (mysettings);//Save changes to the configuration file CONFIG. Save (configurationsavemode.modified);//Forces the connectionstrings configuration section of the configuration file to be re-loaded 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>privatestaticstringgetappconfig (StringstrKey) { foreach (stringkeyinconfigurationmanager.appsettings) {if (key = = strkey) {returnconfigurationmanager.appsettings[ Strkey];}} Returnnull;} 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> Privatestaticvoidupdateappconfig (stringnewkey,stringnewvalue) {boolismodified =false;foreach ( Stringkeyinconfigurationmanager.appsettings) {if (Key==newkey) {ismodified =true;}}  //Open App. Config of Executableconfigurationconfig =configurationmanager.openexeconfiguration ( Configurationuserlevel.none);//need to remove the old Settings object before you can replace itif (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, in the Add New Item dialog box that appears, select Add Application profile, or if the project does not previously have 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 is 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: Please note: If your SQL version is 2005 Express Edition, the default installation of SQL Server instance named Localhost\sqlexpress, you must change the following instance in the "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 id=sa;password=******** "providername=" System.Data.SqlClient "/></connectionstrings>3. AppSettings configuration section: The appsettings configuration section is the configuration of the entire program, and 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 to read and write to the app. Config file, 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> Privatestaticstringgetconnectionstringsconfig (stringconnectionname) {stringconnectionstring = Configurationmanager.connectionstrings[connectionname]. Connectionstring.tostring (); Console.WriteLine (connectionString); returnconnectionstring;} 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 </param> Privatestaticvoidupdateconnectionstringsconfig (stringnewname,stringnewconstring,stringnewprovidername) { Boolismodified =false;//Records If the connection string already exists//if the connection string to be changed already exists if (Configurationmanager.connectionstrings[newname]!=null) { IsModified =true;} Create a new connection string instance Connectionstringsettingsmysettings =newconnectionstringsettings (NewName, newconstring, Newprovidername);//Open the executable configuration file *.exe.configconfigurationconfig =configurationmanager.openexeconfiguration ( Configurationuserlevel.none);//If the connection string already exists, first remove it if (ismodified) {config. ConnectionStrings.ConnectionStrings.Remove (newName);} Adds a new connection string to the configuration file. Config.ConnectionStrings.ConnectionStrings.Add (mysettings);//Save changes to the configuration file CONFIG. Save (configurationsavemode.modified);//Forces the connectionstrings configuration section of the configuration file to be re-loaded 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>privatestaticstringgetappconfig (StringstrKey) { foreach (stringkeyinconfigurationmanager.appsettings) {if (key = = strkey) {returnconfigurationmanager.appsettings[ Strkey];}} Returnnull;} 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> Privatestaticvoidupdateappconfig (stringnewkey,stringnewvalue) {boolismodified =false;foreach ( Stringkeyinconfigurationmanager.appsettings) {if (Key==newkey) {ismodified =true;}}  //Open App. Config of Executableconfigurationconfig =configurationmanager.openexeconfiguration ( Configurationuserlevel.none);//need to remove the old Settings object before you can replace itif (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

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.