配置文件相关

.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);
                }
            }
        }

时间: 2024-08-01 06:43:43

配置文件相关的相关文章

NGINX----源码阅读---数据结构---配置文件相关

1 typedef struct { 2 ngx_file_t file; 3 ngx_buf_t *buffer; 4 ngx_buf_t *dump; 5 ngx_uint_t line; 6 } ngx_conf_file_t; core/ngx_conf_file.h buffer:配置文件缓存,在配置文件解析时提供缓存作用. dump: line:当前配置文件解析的行数 file:配置文件的相关信息: core/ngx_file.h struct ngx_file_s { //ngin

Nginx介绍及配置文件相关

Ngingx的特点 (1)模块化设计,较好的扩展性 (2)高可靠性 master(控制)-->worker (3)较低的内存消耗 10000个keep-alive连接在Nginx仅消耗2.5M (4)支持热部署 不停机而更新配置文件.更换日志文件.更新服务器程序版本 基本功能: 静态资源的web服务器,能缓存打开的文件描述符 http,smtp,pop3协议的反向代理服务器,缓存,负载均衡 支持fastCGI(fpm) 模块化,非DOS机制,重新编译Nginx,过滤器zip,SSI及图像大小调整

配置文件相关的代码

1.配置文件监听 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.IO; namespace CSharpStudy { public sealed class ConfigMonitor { /// <summary> /// file path /// </summary>

【MongoDB】3.0 配置文件相关介绍

概述:在启动mongod和mongos时可以通过配置文件来启动控制实例.该配置文件包含的设置同等于mongod和mongos命令选项. 使用配置文件管理mongod和mongos更容易,特别是对于大规模部署.还可以在配置文件中添加注释来解释服务器设置选项. 使用配置文件:要启动mongod和mongos时使用配置文件,通过–config或者-f选项指定配置文件.例:mongod –config /etc/mongod.conf    //–config可以用-f替代mongos –config

三十三、python中configparser配置文件相关操作

配置文件ini [a1]age = 18sex = 'man' [a2]age = 19sex = 'woman'name = False 1.对配置文件进行操作 import configparser con=configparser.ConfigParser()con.read("ini",encoding="utf-8")#获取所有的节点sec=con.sections()print(sec)#获取指定节点下的键值对it=con.items('a2')prin

Mybatis___配置文件相关配置讲解

主配置文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 引入外部资源 -->

NTP常见问题和解决方案&配置文件详解

一.命令:NTP.ntpq.ntpdate ntpd.ntpq.ntpdate1.ntpq -np //输出参数说明    -n:不显示域名#ntpq -np     remote           refid      st t when poll reach   delay   offset  jitter============================================================================== 127.127.1.0   

Httpd安装,request报文以及相关访问控制

1.Centos7系统下实现httpd-2.2的安装,并分别实现prefork.worker.event等几种工作方式 prefork prefork是一个两级进程模型,非线程的模式,其实通过由父进程管理创建子进程,子进程响应的相应的请求的方式来运行的.以prefork模式运行的httpd,在启动之际就预派生fork了一些子进程,然后等待请求.每个子进程只有一个线程,在一个时间点内只能处理一个请求. 优点:成熟.稳定.兼容所有新老模块.进程之间完全独立,无须担心线程安全的问题. 缺点:一个进程相

mysql的安装和基本配置

一.mysql的安装和基本配置 1 安装cmake #./configure#make &&make install 2 安装mysql# yum install ncurses* bison*   # cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/database/mydata -DSYSCONFDIR=/etc -DTMPDIR=/tmp -DWITH_INNOBASE_STORAGE_ENGINE=1 -