Read application configuration files

Source: Internet
Author: User
Tags allkeys

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. receivettings ["connenctionstring"];

The value of the key attribute of the child element following the deletemetadata, for example, deleetmetadata ["connenctionstring"], access the sub-element <add key = "connenctionstring" value = "*"/>. Its return 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 );
}

Reading and Writing configuration files in vs2005
In vs2003, only application configuration files (App. config or web. config) can be read. In vs2005, the configuration file function has been greatly enhanced.
In vs2005, configuration and configurationmanager are generally used for reading and writing application configuration files.
The configurationmanager class provides an access function for the customer application.
After you use the configurationmanager object to open the configuration file, a configuration object is returned.
The code for reading and writing configuration files through a program is as follows:
1. Create the class corresponding to the configuration section in the configuration file. This class must inherit from configurationsection
Public sealed class configurationsections: configurationsection
{
[Configurationproperty ("FILENAME", defaultvalue = "default.txt")]
Public String filename
{
Get
{
Return (string) This ["FILENAME"];
}
Set
{
This ["FILENAME"] = value;
}
}
}
Public sealed class businessspaceconfiguration: configurationsection
{
[Configurationproperty ("FILENAME")]
Public String filename
{
Get
{
Return (string) This ["FILENAME"];
}
Set
{
This ["FILENAME"] = value;
}
}
}

2. Create the configuration file code
Private Static void writeappconfiguration ()
{
Try
{
Configurationsections configdata = new configurationsections ();
Configdata. filename = "abc.txt ";
System. configuration. Configuration Config = configurationmanager. openexeconfiguration (configurationuserlevel. None );
Config. Sections. Remove ("configurationsections ");
Config. Sections. Add ("configurationsections", configdata );
Config. Save ();

Businessspaceconfiguration bsconfigdata = new businessspaceconfiguration ();
Bsconfigdata. filename = "def.txt ";
System. configuration. Configuration config1 = configurationmanager. openexeconfiguration (configurationuserlevel. None );
Config1.sections. Remove ("businessspaceconfiguration ");
Config1.sections. Add ("businessspaceconfiguration", bsconfigdata );
Config1.save ();
}
Catch (exception ERR)
{
Console. Write (ERR. Message );
}
}

3. The configuration file format is as follows:
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Section name = "businessspaceconfiguration" type = "leleapplication1.businessspaceconfiguration, leleapplication1, version = 1.0.0.0, culture = neutral, publickeytoken = NULL"/>
<Section name = "configurationsections" type = "leleapplication1.configurationsections, leleapplication1, version = 1.0.0.0, culture = neutral, publickeytoken = NULL"/>
</Configsections>
<Businessspaceconfiguration filename = "def.txt"/>
<Configurationsections filename = "abc.txt"/>
</Configuration>

3. Read the application configuration file
Private Static void readappconfiguration ()
{
Configurationsections obj1 = configurationmanager. getsection ("configurationsections") as configurationsections;
Businessspaceconfiguration obj2 = configurationmanager. getsection ("businessspaceconfiguration") as businessspaceconfiguration;
Console. writeline (obj1.filename );
Console. writeline (obj2.filename );

}

Custom Application configuration file (App. config)
1. configuration file Overview:
The 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.

Common configuration file modes:

<Configuration>
<Configsections> // The configuration section declaration area, including the configuration section and namespace declaration.
<Section> // configuration section Declaration
<Sectiongroup> // defines the configuration section group.
<Section> // configuration section declaration in the configuration section group
<Deleetask> // predefined configuration section
<Custom element for configuration section> // configuration section setting area

2. Only the configuration file and access method of the deleettings section are available.

The following is an example of the most common application configuration file, which only contains the appsettings section.

<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Deleetask>
<Add key = "connectionstring" value = "User ID = sa; Data Source =.; Password =; initial catalog = test; provider = sqloledb.1;"/>
<Add key = "templatepath" value = "template"/>
</Appsettings>
</Configuration>
Next let's take a look at how such a configuration file works.

String _ connectionstring = configurationsettings. etettings ["connectionstring"];

You can use the static attribute of the configurationsettings class to directly obtain the configuration information in the configuration file. The type of this attribute is namevaluecollection.
3. Custom configuration file
3.1 custom configuration section

A custom configuration section is divided into two parts in the configuration file: first, declare the configuration section in the <configsections> </configsections> Configuration section ("<section>" in the preceding configuration file mode "), in addition, after <configsections> </configsections>, set the configuration section ("<custom element for configuration section>" in the preceding configuration file mode). It is similar to a variable that is declared first, and later use the same. The statement for declaring a configuration file is as follows:

<Section name = "" type = ""/>
<Section>: declare the new configuration section to create a new configuration section.

Name: name of the custom configuration section.

Type: Type of the custom configuration section, including system. configuration. singletagsectionhandler, system. configuration. dictionarysectionhandler, and system. configuration. namevaluesectionhandler.

Different types not only have different configuration section settings, but also have different operations to access the configuration file. The following is an example of a configuration file that contains the 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 will describe the above custom configuration section. In the declaration section, use <section name = "test1" type = "system. configuration. singletagsectionhandler"/> to declare a configuration section named test1 and its type is singletagsectionhandler. In the Configuration Setting section, use <test1 setting1 = "hello" setting2 = "world"/> to set a configuration section. Its first value is hello, the second value is world. Of course there can be more. The other two configuration sections are similar to this one.
The following describes how to access these custom configuration sections in the program. We used the static method getconfig of the configurationsettings class to get information about the custom configuration section.

Public static object getconfig (string sectionname );

The following code accesses these 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

// Method 2 for accessing test1 in configuration section
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
Through the code above, we can see that different types returned by getconfig are different, and the specific methods for obtaining configuration content are different. Configuration section Handler
Return type

Singletagsectionhandler
Systems. Collections. idictionary

Dictionarysectionhandler
Systems. Collections. idictionary

Namevaluesectionhandler
Systems. Collections. Specialized. namevaluecollection

3.2 custom configuration section group
The configuration section group uses the <sectiongroup> element to group similar configuration sections to the same group. In the configuration section group declaration section, the configuration section inclusion elements are created, the configuration section group is declared in the <configsections> element, and the sections belonging to the group are placed in the <sectiongroup> element. The following is an example of a configuration file containing the 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>
The following code accesses the Configuration group:
Namevaluecollection NC = (namevaluecollection) configurationsettings. getconfig ("testgroup/test ");
MessageBox. Show (nc. allkeys [0]. tostring () + "" + NC ["hello"]); // output Hello World

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.