标签:
.NET中的配置文件App.config的读取和写入需要引用System.Configuration,若读取WCF相关配置需要System.ServiceModel.Configuration.
一、自定义ConfigurationSection
继承ConfigurationSection,并为每一个成员使用标签ConfigurationProperty。IsRequired=true表示必须赋值,否则会返回异常。通过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"]; }
}
}
}
App.config中内容:
自定义的section需要在configSections中声明,需要注意section的type类型,这里是“程序集(命名空间)+类名,程序集(命名空间)”
<?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>
二、自定义ConfigurationElement
上面只是在testSection中添加了属性,现在继续向testSection中添加元素。元素继承自ConfigurationElement。
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);
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 (testElement)base["testElement"]; }
}
}
public class testElement : ConfigurationElement
{
[ConfigurationProperty("ElementName", IsRequired = true)]
public string ElementName
{
get { return (string)base["ElementName"]; }
}
}
}
App.config
<?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>
三、自定义ConfigurationSectionGroup
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Configuration 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=true)]
public string Name
{
get { return (string)base["Name"]; }
}
[ConfigurationProperty("datetime")]
public DateTime datetime
{
get { return (DateTime)base["datetime"]; }
}
[ConfigurationProperty("testElement")]
public testElement element
{
get { return (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 = true)]
public string ElementName
{
get { return (string)base["ElementName"]; }
}
}
}
App.config
<?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>
四、自定义ConfigurationSectionCollection
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Configuration 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.AddRemoveClearMap)]
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 Key
{
get { return (string)base["Key"]; }
}
[ConfigurationProperty("Value")]
public string Value
{
get { return (string)base["Value"]; }
}
}
App.config
<?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>
五、在四中的配置文件的myCollection字段需要添加Add,其实可以直接使用myKevValue。对四中的代码略修改如下:
[ConfigurationCollection(typeof(myKevValue), AddItemName = "myKevValue", CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public class myCollection : ConfigurationElementCollection
{
//省略。。。
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>
六、读取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>
七、读取system.ServiceModel中的配置
有如下WCF配置文件:
<?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>
<ws2007HttpBinding>
<binding name="2007Binding">
<security mode="None"/>
</binding>
</ws2007HttpBinding>
</bindings>
<services>
<service name="service1" behaviorConfiguration="mex">
<endpoint address="http://localhost:8888" binding ="wsHttpBinding" contract="IReadFile"/>
<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>
读取代码如下:
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("<service name=\"{0}\" behaviorConfiguration=\"{1}\">", service.Name, service.BehaviorConfiguration);
foreach (ServiceEndpointElement endpointEle in service.Endpoints)
{
Console.WriteLine("<endpoint address=\"{0}\" binding =\"{1}\" bindingConfiguration=\"{2}\" contract=\"{3}\"/>",
endpointEle.Address, endpointEle.Binding, endpointEle.BindingConfiguration, endpointEle.Contract);
}
}
}

标签:
原文地址:http://www.cnblogs.com/lh218/p/4734481.html