In many cases we need to customize our own Custom app. Config file, and Microsoft provides us with the default
System.Configuration.DictionarySectionHandler
System.Configuration.NameValueSectionHandler
System.Configuration.SingleTagSectionHandler
DictionarySectionHandler use
DictionarySectionHandler works almost the same way as Namevaluefilesectionhandler, the difference being that DictionarySectionHandler returns Hashtable objects, And the latter returned the NameValueCollection.
1 <configsections>2 < Sectionname= "MailServer"type= "System.configuration.dictionarysectionhandler,system, version=4.0.0.0, Culture=neutral, PublicKeyToken= b77a5c561934e089 "/>3 </configsections>4 <mailserver>5 <AddKey= "url"value= "Mail.163.com"/>6 <AddKey= "username"value= "Admin"/>7 <AddKey= "Password"value= "123456"/>8 </mailserver>
Using code
1IDictionary dic = Configurationmanager.getsection ("mailserver") asIDictionary;2 Console.WriteLine (DIC);3 foreach(varKeyinchDiC. Keys)4 {5Console.WriteLine ("{0}:{1}", Key, Dic[key]);6 }7Console.readkey ();
Because DictionarySectionHandler returns a Hashtable object, the key in Hashtable is unique. Then DictionarySectionHandler if the same key is configured, the value that follows will overwrite the previous value.
Or the above example, we will modify the configuration file
1 <mailserver>2 <AddKey= "url"value= "Mail.163.com"/>3 <AddKey= "username"value= "Admin"/>4 <AddKey= "Password"value= "123456"/>5 <AddKey= "Password"value= "12345678"/>6 </mailserver>
Next look at the output:
NameValueSectionHandler use
XML configuration
1 <configsections>2 < Sectionname= "MailServer"type= "System.configuration.namevaluesectionhandler,system, version=4.0.0.0, Culture=neutral, PublicKeyToken= b77a5c561934e089 "/>3 </configsections>4 <mailserver>5 <AddKey= "url"value= "Mail.163.com"/>6 <AddKey= "username"value= "Admin"/>7 <AddKey= "Password"value= "123456"/>8 <AddKey= "Password"value= "12345678"/>9 </mailserver>
Code:
1NameValueCollection mailserver = configurationmanager.getsection ("mailserver") asNameValueCollection;2 Console.WriteLine (mailserver);3 foreach(varKeyinchMailserver.allkeys)4 {5Console.WriteLine ("{0}:{1}", Key,mailserver[key]);6 }7Console.readkey ();
Output Result:
configsections configuration of C # configuration file (ii)