First, preview how. net20 reads the configuration file (Web. config.
-----
The. net20 class for reading the configuration file is the webconfigurationmananger class.
Read the appsettings and connectionstrings sections for preview.
/× Remarks:
<Deleetask>
<Add key = "***" value = "***"/>
</Appsettings>
<Connectionstrings>
<Add name = "***" connectionstring = "***" providername = "***"/>
</Connectionstrings>
×/
There is a direct API to read these two nodes:
Webconfigurationmanager. deleetask[ "Node key"]
Webconfigurationmananger. connectionstrings ["node name"]. connectionstring;
-----
The getsection () method is used below.
Before implementation, you need to know the related classes.
Appsettings corresponds to the appsettingssection class, And the keyValue set is returned for the settings attribute, which corresponds to the key and value respectively.
Connectionstrings corresponds to the connectionstringssection class, which has a connectionstrings attribute and returns connectionstringsettingscollection.
The connectionstringsettings class has the name, connectionstring, and providername attributes, which correspond to corresponding settings.
----
Read the settings in the deletebench cyclically 1 Configuration config = Webconfigurationmanager. openwebconfiguration (request. applicationpath );
2 Appsettingssection appsection = (Appsettingssection) config. getsection ( " Appsettings " );
3 String List = "" ;
4 String [] Appkeys = Appsection. settings. allkeys;
5 For ( Int I = 0 ; I < Appsection. settings. Count; I ++ )
6 {
7 List + = " <Br/> key: " + Appkeys [I] + " , Value: " + Appsection. settings [appkeys [I]. Value + " <Br/> " ;
8 }
9 Readappsettingsresult. Text = List;
Delete or modify a configuration 1 Configuration config = Webconfigurationmanager. openwebconfiguration (request. applicationpath );
2 Appsettingssection appsection = (Appsettingssection) config. getsection ( " Appsettings " );
3 Try
4 {
5 Appsection. settings. Remove ( " Testadd " );
6 // Appsection. settings ["testadd"]. value = "testabc"; modify the value
7 Config. Save (); // Remember to save
8 Removeappsettingresult. Text = " Deleted " ;
9 }
10 Catch (System. Exception ee)
11 {
12Removeappsettingresult. Text= "Deletion failed";
13}
-------- Pay special attention to config. Save () when modifying and deleting the statement. without adding this statement, it will be ineffective.
---- The principles and methods for reading or modifying connectionstrings are the same.