C # Full introduction to app. config

Source: Internet
Author: User
Tags allkeys connectionstrings
C # Read and Write Data in APP. config

[Turn]: http://gb2013.blog.163.com/blog/static/21735301201021253713453/

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>

System. configuration. configurationsettings. receivettings ["key"];
However, framework2.0 clearly indicates that this attribute is out of date. We recommend that you change it 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 system. configuration. DLL to the project.ProgramSet Reference. (In solution manager, right-click the project name and choose add reference from the context menu ,. net tablepage.) After adding a reference, you can use string STR = configurationmanager. appsettings ["key"] to obtain the corresponding value.

Update the configuration file:
Configuration CFA = configurationmanager. openexeconfiguration (configurationuserlevel. None );
CFA. shortettings. settings. Add ("key", "name") | CFA. shortettings. settings ["browsedir"]. value = "name ";

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. 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 () + "Co De.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. Use a program to read and write configuration filesCodeAs 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 Configuration File Code
Private Static void writeappconfiguration ()
{< br> try
{< br> 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 format of the generated configuration file is as follows:
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Section

Type = "leleapplication1.businessspaceconfiguration, consoleapplication1, version = 1.0.0.0,

Culture = neutral, publickeytoken = NULL "/>
<Section type = "leleapplication1.configurationsections,

Leleapplication1, version = 1.0.0.0, culture = neutral, publickeytoken = NULL "/>
</Configsections>
<Businessspaceconfiguration filename = "def.txt"/>
<Configurationsections filename = "abc.txt"/>
</Configuration>

4. 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 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 "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 a configuration file

Example to include the three different types.

The red part is not mentioned in the original post. If the encoding is not involved, an error will occur.
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Section type = "system. configuration. singletagsectionhandler" Name = "test1"/>
<Section type = "system. configuration. dictionarysectionhandler" Name = "Test2"/>
<Section type = "system. configuration. namevaluesectionhandler" Name = "test3"/>
</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 type = "system. configuration. singletagsectionhandler"/> to declare a configuration section named test1 and the 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

Namespace of namevaluecollection: using system. Collections. Specialized
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>
<Section 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

Configure app. config

1. Add the app. config file to the project:

Right-click the project name and select "add"> "Add new item". In the displayed "Add new item" dialog box, 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 name of the SQL server instance is localhost \ sqlexpress by default. You must change the "da"Ta source = localhost; "is" da"Ta 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 providername = "system. DaTa. sqlclient "/>
</Connectionstrings>

3. appsettings configuration section:

The appsettings configuration section is the configuration of the entire program. If you configure the current user, use the usersettings configuration section. The format is the same as the following configuration writing requirements.

<! -- Parameters required for invoicing management system initialization -->
<Deleetask>
<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

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 connectionstrings configuration section

/// <Summary>
/// Connectionname returns the data connection string based on the connection string name
/// </Summary>
/// <Param> </param>
/// <Returns> </returns>
Private Static string getconnectionstringsconfig (string connectionname)
{
String connectionstring =
Configurationmanager. connectionstrings [connectionname]. connectionstring. tostring ();
Console. writeline (connectionstring );
Return connectionstring;
}

4.2 connectionstrings configuration update

/// <Summary>
/// Update the connection string
/// </Summary>
/// <Param> connection string name </param>
/// <Param> connection string content </param>
/// <Param> 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 changes made to the configuration file
Config. Save (configurationsavemode. modified );
// Force re-load the connectionstrings configuration section of the configuration file
Configurationmanager. refreshsection ("connectionstrings ");
}

4.3 read the appstrings configuration section

/// <Summary>
/// Return the value item in the configuration section of the ettings in *. EXE. config file.
/// </Summary>
/// <Param> </param>
/// <Returns> </returns>
Private Static string getappconfig (string strkey)
{
Foreach (string key in configurationmanager. receivettings)
{
If (Key = strkey)
{
Return configurationmanager. deleetask[ strkey];
}
}
Return NULL;
}

4.4 connectionstrings configuration update

///


/// in *. EXE. add a pair of key and value pairs to the deleettings configuration section in the config file
///
///
// /
Private Static void updateappconfig (string newkey, string newvalue)
{< br> bool ismodified = false;
foreach (string key in configurationmanager. ettings)
{< br> If (Key = newkey)
{< br> ismodified = true;
}< BR >}

// 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)
{< br> config. appsettings. settings. remove (newkey);
}< br> // 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.