App. config

Source: Internet
Author: User
Tags connectionstrings

App. ConfigThe application configuration file is a standard XML file, and the XML tag and attribute are case sensitive. It can be changed as needed. developers can use the configuration file to change the settings without re-compiling the application.
The root node of the configuration file is configuration. We often access the deleettings, which is a pre-defined configuration section by. Net. The architecture of frequently used configuration files is in the following format.
First, I have an impression that I will have a clear understanding through the following examples. The "configuration section" below can be understood as configuring an XML node.
1. add an app to the project. config File: Right-click the project name and choose "add"> "Add new item". In the "Add new project" dialog box that appears, select "add application configuration file "; if the project has no configuration file before, the default file name is "app. config, and click OK ". The app. config file that appears in the designer view is: <? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> </configuration> after the project is compiled, two configuration files (this project is used as an example) will appear under the bin/Debuge file, one named "JxcManagement. EXE. config, And the other name is "JxcManagement.vshost.exe. config ". The first file is the configuration file actually used by the project. All changes made during the program running will be saved here. The second file is the original code "app. config. 2. connectionStrings configuration section: Note: If your SQL version is 2005 Express, the SQL server instance name is localhost/SQLExpress by default, and you must change "Data Source = localhost; "is" Data Source = localhost/SQLExpress; ". Do not add spaces on both sides of the equal 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: the appSettings configuration section is the configuration of the entire program. to configure the current user, use the userSettings configuration section. The format is the same as the following configuration requirements. <! -- Parameters required for invoicing management system initialization --> <deleettings> <clear/> <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 the app. config for app. config File Read and Write, refer to the network article: http://www.codeproject.com/csharp/ SystemConfiguration. asp The title is "Read/Write App. Config File with. NET 2.0. Note: To use the following code to access the app. config file, in addition to adding a reference to System. Configuration, you must also add a reference to System. Configuration. dll in the project. 4.1 read the connectionStrings configuration section /// <summary> /// return the data connection string based on the connectionName of the connection string /// </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 the 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; // record whether the connection string already exists // if the connection string to be modified already exists if (ConfigurationManager. ConnectionStrings [newName]! = Null) {isModified = true;} // create a 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, delete it first if (isModified) {config. connectionStrings. connectionStrings. remove (newName);} // Add a new connection string to the configuration file. config. connectionStrings. connectionStrings. add (mySettings); // Save the configuration file changes. save (ConfigurationSaveMode. modified); // force the ConnectionStrings configuration section of the configuration file to be reloaded. refreshSection ("ConnectionStrings");} 4.3 read the appStrings configuration section // <summary> // return *. exe. the value item in the configuration section of the deleettings configuration section in the 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> /// in *. exe. add a key pair and value pair to the deleettings configuration section in the config file /// </summary> /// <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); // You 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 ("receivettings ");

}

C # Read and Write Data in app. config

Read statement:

String str = ConfigurationManager. receivettings ["DemoKey"];

Write statement:

Configuration cfa = ConfigurationManager. OpenExeConfiguration (ConfigurationUserLevel. None );
Cfa. deleetask. Settings ["DemoKey"]. Value = "DemoValue ";
Cfa. Save ();

Configuration file content format: (app. config)

<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "DemoKey" value = "*"/>
</AppSettings>
</Configuration>

 Several key sections marked with red pens are required

System. Configuration. ConfigurationSettings. receivettings ["Key"];

However, FrameWork2.0 clearly indicates that this attribute is out of date. It is recommended to change to ConfigurationManager.

Or WebConfigurationManager. The AppSettings attribute is read-only and does not support modifying attribute values.

However, to call ConfigurationManager, you must first Add a reference to the system. configuration. dll assembly in the project.

(In solution manager, right-click the project name and choose add reference from the shortcut menu. net TablePage)
After adding a reference, you can use String str = ConfigurationManager. etettings ["Key"] to obtain the corresponding value.

Update the configuration file:

Configuration cfa = ConfigurationManager. openExeConfiguration (ConfigurationUserLevel. none); cfa. appSettings. settings. add ("key", "Name") | cfa. appSettings. settings ["BrowseDir"]. value = "name ";

And so on...
Last call
Cfa. Save ();
The current configuration file is updated successfully.

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

Read and Write the configuration file app. config
The configuration file is provided in. Net, which allows us to Process configuration information in a very good way. This configuration is in XML format. In addition,. Net provides some functions to access this file.

1. Read configuration information
The specific content of a configuration file is as follows:

 

<? Xml version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "ConnenctionString" value = "*"/>
<Add key = "TmpPath" value = "C: \ Temp"/>
</AppSettings>
</Configuration>

. Net provides a method to directly access the <etettings> (case-sensitive) element. There are many child elements in this element, and the names of these child elements are "add ", there are two attributes: "key" and "value ". In general, we can write our configuration information in this area and access it through the following methods:

 

 

String ConString = System. configuration. configurationSettings. appSettings ["ConnenctionString"]; the value of the key attribute of the sub-element is after the deleettings, for example, appsettings ["connenctionstring"], this is the subelement <add key = "ConnenctionString" value = "*"/>. The returned value is "*", that is, the value of the value attribute.

2. Set 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 a program to implement it. No configuration file is written in. Net. You can operate the configuration file by operating the XML file. The following is an example of writing a configuration file.

 

Private void SaveConfig (string ConnenctionString)
{
XmlDocument doc = new XmlDocument ();
// Obtain the full path of the configuration file
String strFileName = AppDomain. CurrentDomain. BaseDirectory. ToString () + "Code.exe. config ";
Doc. LOAd (strFileName );
// Find all elements named "add"
XmlNodeList nodes = doc. GetElementsByTagName ("add ");
For (int I = 0; I <nodes. Count; I ++)
{
// Obtain the key attribute of the current element
XmlAttribute att = nodes [I]. Attributes ["key"];
// Determine whether the current element is a target element based on the first attribute of the element.
If (att. Value = "ConnectionString ")
{
// Assign values to the second attribute of the target Element
Att = nodes [I]. Attributes ["value"];
Att. Value = ConnenctionString;
Break;
}
}
// Save the modification above
Doc. Save (strFileName );
} Read and modify the App. config file
1. add an app to the project. config File: Right-click the project name and choose "add"> "Add new item". In the "Add new project" dialog box that appears, select "add application configuration file "; if the project has no configuration file before, the default file name is "app. config, and click OK ". The app. config file that appears in the designer view is: <? Xmlversion = "1.0" encoding = "UTF-8"?> <Configuration> </configuration> after the project is compiled, Run "bin \ users. config ". The first file is the configuration file actually used by the project. All changes made during the program running will be saved here. The second file is the original code "app. config. 2. connectionStrings configuration section: Note: If your SQL version is 2005 Express, the Instance name of the SQL Server is localhost \ SQLExpress by default, and you must change "Data Source = localhost; "is" Data Source = localhost \ SQLExpress; ". Do not add spaces on both sides of the equal 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. to configure the current user, use the userSettings configuration section. The format is the same as the following configuration requirements. <! -- Parameters required for invoicing management system initialization --> <deleettings> <clear/> <addkey = "userName" value = ""/> <addkey = "password" value = ""/> <addkey = "Department" value = ""/> <addkey = "returnValue" value = ""/> <addkey = "pwdPattern" value = ""/> <addkey = ""userPattern" value = ""/> </appSettings> 4. read and update the app. config for app. config File Read and Write, refer to the network article: http://www.codeproject.com/csharp/ SystemConfiguration. asp is titled "Read/Write App. config File. NET 2.0. Note: To use the following code to access the app. config file, in addition to adding a reference to System. Configuration, you must also add a reference to System. Configuration. dll in the project. 4.1 read the connectionStrings configuration section /// <summary> /// return the data connection string based on the connectionName of the connection string /// </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 conne CtionStrings configuration section /// <summary> /// update the 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; // record whether the connection string already exists // if the connection string to be modified already exists if (ConfigurationManager. connectionStrings [newNa Me]! = Null) {isModified = true;} // create a 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, delete it first if (isModified) {config. connectionStrings. connectionStrings. remove (newName);} // Add a new connection string to the configuration file. config. connectionStrings. connectionStrings. add (mySettings); // Save the configuration file changes. save (ConfigurationSaveMode. modified); // force the ConnectionStrings configuration section of the configuration file to be reloaded. refreshSection ("ConnectionStrings");} 4.3 read the appStrings configuration section // <summary> // return *. exe. the value item in the configuration section of the deleettings configuration section in the 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> /// in *. exe. add a key pair and value pair to the deleettings configuration section in the config file /// </summary> /// <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); // You 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 ("receivettings ");}

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.