C # application configuration file. config Introduction

Source: Internet
Author: User
Tags allkeys connectionstrings

We often want to write some configuration information in the program, such as the version number, the connection string for the database, and so on. You may know that you can use Properties.settings to do similar work in WinForm applications, but these actually take advantage of the app. config profile. This article explores how to access the app. Config method in code. The use of App. Config is far more complex than the one mentioned above, so only the most basic AppSettings configuration section is discussed.

1. configuration file Overview:
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.

Common Configuration file modes:

<Configuration><configsections>//configuration section Declaration area, including configuration section and namespace declaration< Section>//configuration section declaration<sectiongroup>//Define configuration section groups< Section>configuration section declarations in the//configuration section group<appSettings>//Pre-defined configuration section<Customelement for configuration section>Configuration section Settings area

2. config configuration file configuration section

(1) General configuration section

  < appSettings >    <  key= "CONNSTR1"  value= "User id=sa;data source=.; Password=;initial catalog=test; Provider=SQLOLEDB.1; " />  </ appSettings >

(2) Data Source configuration section

  < connectionStrings >    <  name= "CONNSTR2"  connectionString= "Localsqlserver:data source=127.0.0.1 ; Integrated security=sspi;initial catalog=aspnetdb "  providerName=" System.Data.SqlClient "  />  </connectionStrings>

Complete as follows

<?XML version= "1.0" encoding= "Utf-8"?><Configuration>  <appSettings>    <AddKey= "CONNSTR1"value= "User id=sa;data source=.; Password=;initial catalog=test; Provider=SQLOLEDB.1; " />  </appSettings>  <connectionStrings>    <Addname= "CONNSTR2"connectionString= "Localsqlserver:data source=127.0.0.1;integrated security=sspi;initial catalog=aspnetdb"ProviderName= "System.Data.SqlClient" />  </connectionStrings></Configuration>

Here's a look at how this configuration file is accessed. Usage Prerequisites:

① Add Reference System.Configuration

② Introducing namespaces

using System.Configuration;
string _connstr1 = configurationmanager.appsettings["ConnStr1"]; string _connstr2 = configurationmanager.connectionstrings["ConnStr2"]. ToString ();         

(3) Custom configuration section

A user-defined configuration section that is divided into two parts in the configuration file: First, the configuration section is declared in the <configsections></configsections> configuration section ("<section>" in the configuration file mode above)

In addition, set the configuration section after <configsections></configsections > (the "<custom element for configuration > "), a bit like a variable declared first, and then used the same. The statement that declares a configuration file is as follows:

<section name= "" type= ""/>
<section>: Declares a new configuration section to create a new configuration section.

Name: The names of the custom configuration sections.

Type: The types of custom configuration sections, mainly including System.Configuration.SingleTagSectionHandler, System.Configuration.DictionarySectionHandler, System.Configuration.NameValueSectionHandler.

Different types not only set the configuration section differently, but there are also differences in the operation of the last access configuration file. Let's give an example of a configuration file that contains these three different types.

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<configSections>
<section name= "Test1" type= "System.Configuration.SingleTagSectionHandler"/>
<section name= "Test2" type= "System.Configuration.DictionarySectionHandler"/>
<section name= "Test3" type= "System.Configuration.NameValueSectionHandler"/>
</configSections>

<test1 setting1= "Hello" setting2= "World"/>
<Test2>
<add key= "Hello" value= "World"/>
</Test2>
<Test3>
<add key= "Hello" value= "World"/>
</Test3>
</configuration>

We describe the custom configuration section above. In the Declaration section use <section name= "Test1" type= "System.Configuration.SingleTagSectionHandler"/> declares a configuration section its name is Test1, The type is SingleTagSectionHandler. In the Set configuration section section, use <test1 setting1= "Hello" setting2= "World"/> Set a configuration section, its first setting value is Hello, the second value is world, and of course there are more. The other two configuration sections are similar to this one.
Let's look at how these custom configuration sections are accessed in the program. We have used the static method of the ConfigurationSettings class GetConfig to get the information for the custom configuration section.

public static Object GetConfig (string sectionname);

Here is the code to access the three configuration sections:

Access configuration section Test1
IDictionary IDTest1 = (IDictionary) configurationsettings.getconfig ("Test1");
String str = (string) idtest1["setting1"] + "" + (String) idtest1["Setting2"];
MessageBox.Show (str); Output Hello World

To access configuration section Test1 Method 2
String[] Values1=new String[idtest1.count];
IDTest1.Values.CopyTo (values1,0);
MessageBox.Show (values1[0]+ "" +values1[1]); Output Hello World

Access configuration section Test2
IDictionary IDTest2 = (IDictionary) configurationsettings.getconfig ("Test2");
String[] Keys=new String[idtest2.keys.count];
String[] Values=new String[idtest2.keys.count];
IDTest2.Keys.CopyTo (keys,0);
IDTest2.Values.CopyTo (values,0);
MessageBox.Show (keys[0]+ "" +values[0]);

Access configuration section Test3
NameValueCollection nc= (NameValueCollection) configurationsettings.getconfig ("Test3");
MessageBox.Show (NC. Allkeys[0].    ToString () + "" +nc["Hello"]); Output Hello World

As we can see from the above code, different types are returned by GetConfig differently, and the exact way to get the configuration content is different. Configuration section Handlers
return type

SingleTagSectionHandler
Systems.Collections.IDictionary

DictionarySectionHandler
Systems.Collections.IDictionary

NameValueSectionHandler
Systems.Collections.Specialized.NameValueCollection

3.2 Custom Configuration section groups
A configuration section group uses the <sectionGroup> element to divide a similar configuration section into the same group. The configuration section Group Declaration section creates the containing element of the configuration section, declares the configuration section group in the <configSections> element, and places the section that belongs to the group in the <sectionGroup> element. The following is an example of a configuration file that contains a configuration section group:

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<configSections>
<sectiongroup name= "Testgroup" >
<section name= "Test" type= "System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>

<TestGroup>
<Test>
<add key= "Hello" value= "World"/>
</Test>
</TestGroup>
</configuration>
Here is the code to access this configuration section group:
NameValueCollection nc= (NameValueCollection) configurationsettings.getconfig ("Testgroup/test");
MessageBox.Show (NC. Allkeys[0].    ToString () + "" +nc["Hello"]); Output Hello World

C # application configuration file. config Introduction

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.