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 writeProgram . 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 the elements named "add"
Xmlnodelist nodes = Doc. getelementsbytagname ( " Add " );
For ( Int I = 0 ; I < Nodes. Count; I ++ )
{
// Obtains 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 a value to the second attribute of the target element.
ATT = Nodes [I]. attributes [ " Value " ];
Att. Value = Connenctionstring;
Break ;
}
}
// Save the above changes
Doc. Save (strfilename );
}