. The read and write of the config file in the. NET application requires reference to System.Configuration, which requires System.ServiceModel.Configuration to read the WCF-related configuration.
One, Custom ConfigurationSection
Inherit the ConfigurationSection and use the label ConfigurationProperty for each member. Isrequired=true indicates that a value must be assigned, otherwise an exception is returned. Set default values through DefaultValue.
Namespace consoleapplication2{ class program { static void Main (string[] args) { Configuration Configuration = Configurationmanager.openexeconfiguration (Configurationuserlevel.none); Testsection test = (testsection) configuration. GetSection ("Testsection"); Console.WriteLine ("Testsection:name={0} datetime={1}", Test. Name, test.datetime); } } public class testsection:configurationsection { [ConfigurationProperty ("Name", Isrequired=true, Defaultvalue= "Testsection")] public string Name { get {return (string) base["name"]; } [ConfigurationProperty ("datetime")] public datetime datetime { get {return (datetime) base["datetime"];} } }
Content in app. config:
Custom sections need to be declared in configsections, note the type of the section, which is "assembly (namespace) + class name, assembly (namespace)"
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <section Name = "Testsection" type= "Consoleapplication2.testsection,consoleapplication2"/> </configSections> <testsection name= "test1" datetime= "2015-08-06 13:26:00"/></configuration>
Second, custom ConfigurationElement
The above just adds the attributes in Testsection, and now continues to add elements to testsection. Element inherits from ConfigurationElement.
Namespace consoleapplication2{class Program {static void Main (string[] args) {Configurat Ion configuration = Configurationmanager.openexeconfiguration (Configurationuserlevel.none); Testsection test = (testsection) configuration. GetSection ("Testsection"); Console.WriteLine ("Testsection:name={0} datetime={1}", Test. Name, Test.datetime); Console.WriteLine ("\telement:elementname={0}", Test.element.ElementName); }} public class Testsection:configurationsection {[ConfigurationProperty ("Name", Isrequired=true)] public string Name {get {return (string) base["name"];} } [ConfigurationProperty ("datetime", Defaultvalue=datetime.now)] public datetime datetime { get {return (datetime) base["datetime"];} } [ConfigurationProperty ("Testelement")] public testelement element {get {return (Testel ement) base["TEstelement "]; }}} public class Testelement:configurationelement {[ConfigurationProperty ("ElementName", Isreq Uired = True)] public string ElementName {get {return (string) base["ElementName"];} } }}
App.
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <section Name = "Testsection" type= "Consoleapplication2.testsection,consoleapplication2"/> </configSections> <testsection name= "test1" datetime= "2015-08-06 13:26:00" > <testelement elementname= "ElementName"/> </testSection></configuration>
Third, custom ConfigurationSectionGroup
Namespace consoleapplication2{class Program {static void Main (string[] args) {Configurat Ion configuration = Configurationmanager.openexeconfiguration (Configurationuserlevel.none); MyGroup test = (mygroup) configuration. Getsectiongroup ("MyGroup"); Testsection test1 =test.testsection; TestSection2 test2 = Test.testsection2; Console.WriteLine ("Test1:name={0} Datetime={1}", Test1. Name, Test1.datetime); Console.WriteLine ("\telement:elementname={0}", Test1.element.ElementName); Console.WriteLine ("\test2:name={0}", Test2. Name); }} public class Mygroup:configurationsectiongroup {[ConfigurationProperty ("testsection", isrequired = true)] public testsection testsection {get {return (testsection) base. sections["Testsection"]; }} [ConfigurationProperty ("TestSection2", IsRequired = True)] public testSection2 TestSection2 {get {return (TestSection2) base. sections["TestSection2"]; }}} public class Testsection:configurationsection {[ConfigurationProperty ("Name", isrequired=tr UE)] public string name {get {return (string) base["name"];} } [ConfigurationProperty ("datetime")] public datetime datetime {get {return (datetime) BA Se["datetime"]; }} [ConfigurationProperty ("Testelement")] public testelement element {get {retur N (testelement) base["Testelement"]; }}} public class Testsection2:configurationsection {[ConfigurationProperty ("Name", isrequired = True)] public string name {get {return (string) base["name"];} }} public class Testelement:configurationelement {[ConfigurationProperty ("elementname", isrequired = t Rue)] public string ElementName {get {return (string) base["ElementName"]; } } }}
App.
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> < Sectiongroup name= "MyGroup" type= "Consoleapplication2.mygroup,consoleapplication2" > <section name= " Testsection "type=" Consoleapplication2.testsection,consoleapplication2 "/> <section name=" TestSection2 " Type= "Consoleapplication2.testsection2,consoleapplication2"/> </sectionGroup> </ configsections> <mygroup> <testsection name= "test1" datetime= "2015-08-06 13:26:00" > <testelement elementname= "elementname"/> </testSection> <testsection2 name= "Test2"/> </mygroup></configuration>
Iv. Custom Configurationsectioncollection
Namespace consoleapplication2{class Program {static void Main (string[] args) {Configurat Ion configuration = Configurationmanager.openexeconfiguration (Configurationuserlevel.none); MySection mysection = (mysection) configuration. GetSection ("MySection"); foreach (Mykevvalue kv in mysection.collection) {Console.WriteLine (kv). Key + "" + kv. Value); }}} public class Mysection:configurationsection {[ConfigurationProperty ("mycollection")] Public mycollection Collection {get {return (mycollection) base["mycollection"];} }} [Configurationcollection (typeof (Mykevvalue), CollectionType = Configurationelementcollectiontype.addremoveclear MAP)] public class Mycollection:configurationelementcollection {public Mykevvalue This[int index] { get {return (Mykevvalue) base. Baseget (index); } set {if (null! = base.) Baseget (Index)) {base. Baseremoveat (index); } base. Baseadd (Index,value); }} public Mykevvalue this[string index] {get {return (Mykevvalue) base. Baseget (index); }} protected override ConfigurationElement Createnewelement () {return new Mykevvalue (); } protected Override Object Getelementkey (configurationelement Element) {return (element As Mykevvalue). Key; }} public class Mykevvalue:configurationelement {[ConfigurationProperty (' Key ')] public string K EY {get {return (string) base["Key"];} } [ConfigurationProperty ("Value")] public string Value {get {return (string) base[ "Value"]; } } }
App.
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <section Name = "MySection" type= "Consoleapplication2.mysection,consoleapplication2"/> </configSections> < mysection> <myCollection> <add key= "Key1" value= "Value1"/> <add key= "Key2" value= " Value2 "/> <add key=" Key3 "value=" Value3 "/> </myCollection> </mysection></ Configuration>
Five, the MyCollection field of the configuration file in the four need add, actually can use Mykevvalue directly. The code in the four is slightly modified as follows:
[Configurationcollection (typeof (Mykevvalue), additemname = "Mykevvalue", CollectionType = CONFIGURATIONELEMENTCOLLECTIONTYPE.ADDREMOVECLEARMAP)] public class mycollection: ConfigurationElementCollection { //omitted ... protected override string ElementName { get { return ' Mykevvalue ';}} }
App. Config:
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <configSections> <section Name= "MySection" type= "Consoleapplication2.mysection,consoleapplication2"/> </configSections> <mySection> <myCollection> <mykevvalue key= "Key1" value= "Value1"/> < Mykevvalue key= "Key2" value= "Value2"/> <mykevvalue key= "Key3" value= "Value3"/> </ Mycollection> </mySection></configuration>
Six, read appsettings
Class program { static void Main (string[] args) { Configuration configuration = Configurationmanager.openexeconfiguration (configurationuserlevel.none); Appsettingssection appsettingssection = (appsettingssection) configuration. GetSection ("appSettings"); foreach (String kv in AppSettingsSection.Settings.AllKeys) { Console.WriteLine ("Key={0} Value={1}", KV, APPSETTINGSSECTION.SETTINGS[KV]. Value);}}}
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <appSettings> <add key= "Key1 "Value=" value1 "/> <add key=" Key2 "value=" value1 "/> <add key=" Key3 "value=" Value3 "/> </appSettings></configuration>
Seven, read system. Configuration in the ServiceModel
has the following WCF configuration file:
<?xml version= "1.0" encoding= "Utf-8"?><configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name= "Mex" > <servicemetadata httpgetenabled= "true" httpgeturl= "Http://localhost/mex"/> </behavior> </serviceBehaviors> </behaviors> <bindings& Gt <ws2007HttpBinding> <binding name= "2007Binding" > <security mode= "None"/> </bin ding> </ws2007HttpBinding> </bindings> <services> <service name= "Service1" Beh Aviorconfiguration= "Mex" > <endpoint address= "http://localhost:8888" binding = "Wshttpbinding" contract= "IREADF Ile "/> <endpoint address=" net.tcp://localhost:9999 "binding=" nettcpbinding "contract=" IReadFile "/> <endpoint address= "http://localhost:2007" binding= "ws2007httpbinding" bindingconfiguration= "2007Binding" contract= "Ireadfile"/> </service> </services> </system.serviceModel></configuration>
Read the code as follows:
static void Main (string[] args) {console.windowwidth = 170; Configuration configuration = Configurationmanager.openexeconfiguration (Configurationuserlevel.none); Servicemodelsectiongroup servicemodelsection = (servicemodelsectiongroup) configuration. Getsectiongroup ("System.ServiceModel"); foreach (Servicebehaviorelement serbehaviorele in serviceModelSection.Behaviors.ServiceBehaviors) { Servicemetadatapublishingelement metadate = (servicemetadatapublishingelement) serbehaviorele.elementat (0); Console.WriteLine ("<behavior name=\" {0}\ ">", Serbehaviorele.name); Console.WriteLine ("<{0} httpgetenabled=\" {1}\ "httpgeturl=\" {2}\ "/>", metadate. Behaviortype.name, Metadate. Httpgetenabled, Metadate. Httpgeturl); Console.WriteLine ("</behavior>"); } ws2007httpbindingcollectionelement Bindingele = ServiceModelSection.Bindings.WS2007HttpBinding Ws2007httpbindingelement Ws2007bindingele = (ws2007httpbindingelement) bindingele.configuredbindings[0]; Console.WriteLine ("<binding name=\" {0}\ ">", Bindingele.configuredbindings[0]. Name); Console.WriteLine ("<security mode=\" {0}\ "/>", Ws2007BindingEle.Security.Mode); Console.WriteLine ("<security>"); foreach (serviceelement service in serviceModelSection.Services.Services) {Console.WriteLine ("& Lt;service name=\ "{0}\" behaviorconfiguration=\ "{1}\" > ", Service. Name, service. behaviorconfiguration); foreach (Serviceendpointelement endpointele in service. Endpoints) {Console.WriteLine ("<endpoint address=\" {0}\ "binding =\" {1}\ "Bindingcon Figuration=\ "{2}\" contract=\ "{3}\"/> ", endpointele.address, Endpointele.binding, endpointele.b Indingconfiguration, endpointele.contract); } } }
Configuration file-related