• App.config配置详解


    经上一篇文章https://www.cnblogs.com/luna-hehe/p/9104701.html发现自己对配置文件很是不了解,同样还是查了半天终于发现另一片宝贵文档https://www.cnblogs.com/ysz12300/p/5509576.html  和 https://blog.csdn.net/z702143700/article/details/45913797 和 http://www.cnblogs.com/jhxk/articles/1609182.html(可能是自己用错关键字查询);

    在此只作为自己学习记录的笔记

      配置文件一般分为内置配置文和用户自定义配置文件。

          内置配置文件包括app.config、web.config、Settings.settings( 这个用的不多,操作也很简单,在此不详细叙述)等等。

       用户自定义配置文件一般是将配置信息放到XML文件或注册表中,配置信息一般包括程序设置,记录运行信息,保存控件的信息(比如位置,样式)。

    一、内置配置文件操作

    app.config和web.config操作类似,以app.config为例,Settings.settings能够指定值的类型和范围

    1.app.config文件操作

    该配置文件中主要的节点有:connectionStrings、appSettings、configSections等,这几个属于常用,操作都略有不同,DotNet提供直接操作各个节点的方法。在用到ConfigurationManager时要添加system.configuration.dll程序集的引用。

    程序移植后配置文件的修改会保存在.exe.config的文件中,但是根据我经验如果你不修改配置文件,一般exe不自动创建一个.exe.config的文件。

    在项目进行编译后,在binDebuge文件下,将出现两个配置文件,一个名为“*.EXE.config”,另一个名为“*.vshost.exe.config”。第一个文件为项目实际使用的配置文件,在程序运行中所做的更改都将被保存于此;第二个文件为原代码“app.config”的同步文件,在程序运行中不会发生更改。

    1)默认App.config

    1 <?xml version="1.0" encoding="utf-8" ?>
    2 <configuration>
    3     <startup> 
    4         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    5     </startup>
    6 </configuration>

    说明:无论我是建Windows窗体应用程序,还是控制台应用程序,还是Windows服务默认生成的App.config文件都是长这样的。

    2)  connectionStrings 配置节:用于设置数据库连接字符串
    请注意:如果您的 SQL 版本为 2005 Express 版,则默认安装时 SQL 服务器实例名为localhost/SQLExpress ,须更改以下实例中“ Data Source=localhost; ”一句为“ Data Source=localhost/SQLExpress; ”,在等于号的两边不要加上空格。
    <!-- 数据库连接串 -->
    < connectionStrings >
       < add name = "conJxcBook " connectionString = "Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=******** " providerName = "System.Data.SqlClient " />
    </ connectionStrings >

    下面为我自己的项目中的代码(我本地SQL版本为2012,服务器SQL版本为2008R2,与上面所述不太一样):

     <connectionStrings>
        <add name="ConnectionStringMain" connectionString="Data Source=192.168.1.211;Initial Catalog=WLZhuJianMes;Persist Security Info=True;User ID=sa;Password=sa;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
     </connectionStrings>
    从App.config中读取链接字符串:
    ConfigurationManager.ConnectionStrings["ConnectionStringMain"].ConnectionString;

    往App.config中写入链接字符串

    //设置连接字符串  
      
    ConnectionStringSettings setConnStr = newConnectionStringSettings("AccessDB", connectionString,"System.Data.OleDb");  
      
    //打开当前应用程序的app.config文件,进行操作  
      
    Configuration appConfig =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
      
    //由于没有更新连接字符串的方法,所以这里直接再添加一个连接字符串  
      
    appConfig.ConnectionStrings.ConnectionStrings.Add(setConnStr);  
      
    appConfig.Save();  
      
    // 强制重新载入配置文件的ConnectionStrings配置节  
      
    ConfigurationManager.RefreshSection("connectionStrings");  
    3) appSettings 配置节:主要用于整个程序的配置,以键值对的形式出现
    appSettings 配置节为整个程序的配置,如果是对当前用户的配置,请使用 userSettings 配置节,其格式与以下配置书写要求一样。
     
    < appSettings >
       < add key = "userName "value = "" />
       < add key = "password "value = "" />
       < add key = "Department "value = "" />
       < add key = "returnValue "value = "" />
       < add key = "pwdPattern "value = "" />
       < add key = "userPattern "value = "" />
    </ appSettings >

    在预定义的 appSettings 节(注意大小写),有很多的元素,这些元素名称都是“add”,有两个属性分别是“key”和“value”。

    .NET 提供了对appSettings节的访问方法。在 .NET 1.0 和 1.1 版本中,可以使用 System.Configuration.ConfigurationSettings.AppSettings["Key"] 来对 key = "Key" 的<add>元素的 value属性 进行访问。

    注意:现在.Net FrameWork 2.0中已经明确表示此ConfigurationSettings属性已经废弃,建议改为 ConfigurationManager 或 WebConfigurationManager。

    使用 System.Configuration.ConfigurationManager,需要在工程里添加对 system.configuration.dll 程序集的引用。(在解决方案管理器中右键点击工程名称,在右键菜单中选择添加引用,在.NET选项卡下即可找到。)

    添加引用后,就可以用 ConfigurationManager.AppSettings["Key"] 来读取对应的值了.

    但是,ConfigurationManager.AppSettings 属性是只读的,并不支持修改属性值。这是因为据说微软不太建议我们动态写入app.config文件,而是建议手工配置后,在程序运行时只做静态访问。

    如果实在需要在程序中进行修改,也即写入App.Config,请往下看。

    读:

    String str = ConfigurationManager.AppSettings["userName"];  

    读取App.config文件的appSettings节的方法比较简单,可以通过上文中 System.Configuration.ConfigurationManager.AppSettings["Key"]的方法进行访问,但前面也已经说了,该方法不提供写入。

    如果希望写入配置文件,可以使用ConfigurationManager对象执行打开配置文件的操作后,将会返回一个Configuration的对象,利用该对象进行操作(增删改查都可以哦)。

    下面给出实现的代码(增加引用using System.Configuration名称空间)

    写:

    private void AccessAppSettings()
    {
        //获取Configuration对象
        Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        //根据Key读取<add>元素的Value
        string name = config.AppSettings.Settings["name"].Value;
        //写入<add>元素的Value
        config.AppSettings.Settings["name"].Value = "fx163";
        //增加<add>元素
        config.AppSettings.Settings.Add("url", "http://www.fx163.net");
        //删除<add>元素
        config.AppSettings.Settings.Remove("name");
        //一定要记得保存,写不带参数的config.Save()也可以
        config.Save(ConfigurationSaveMode.Modified);
        //刷新,否则程序读取的还是之前的值(可能已装入内存)
        System.Configuration.ConfigurationManager.RefreshSection("appSettings");
    }

    需要注意的是:

    1、根据并不存在的Key值访问<add>元素,甚至使用remove()方法删除不存在的元素,都不会导致异常,前者会返回null。

    2、add已经存在的<add>元素也不会导致异常,而是concat了已有的Value和新的Value,用","分隔,例如:"olldvalue,newvalue"。

    3、特别注意大小写(XML文件是区分大小写的),例如appSettings配置节。

    4、可能有读者会想到,既然app.config是标准XML,当然也可以用操纵一般XML文件的方法来读写。这当然是可以的!只不过我认为这样就失去了VS提供app.config文件的意义了,还不如自己定义一个配置文件方便。

    4).configSections自定义配置节:自定义configSections,可以自行定义节元素,扩展了appSettings一个节的功能

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="quartz" type="System.Configuration.NameValueSectionHandler"/>
        <section name="sampleSection1" type="System.Configuration.SingleTagSectionHandler"/>
        <section name="sampleSection2" type="System.Configuration.DictionarySectionHandler"/>
      </configSections>
      
      <quartz>
        <add key="quartz.scheduler.instanceName" value="ExampleDefaultQuartzScheduler"/>
        <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>
        <add key="quartz.threadPool.threadCount" value="10"/>
        <add key="quartz.threadPool.threadPriority" value="2"/>
        <add key="quartz.jobStore.misfireThreshold" value="60000"/>
        <add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz"/>
        <!--******************************Plugin配置*********************************************-->
        <add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
        <add key="quartz.plugin.xml.fileNames" value="~/quartz_jobs.xml"/>
      </quartz>
    
      <sampleSection1 setting1="Value1" setting2="value two" setting3="third value" />
    
      <sampleSection2>
        <add key="add" value="id=1"/>
        <add key="edit" value="id=2"/>
      </sampleSection2>

    name属性:指的是自定义配置节的名称,即自定义的这个section的名字,

    type属性:指的是自定义配置节的类型,即用于接收这个section中相应字段的类,主要包括:System.Configuration.SingleTagSectionHandler;System.Configuration.DictionarySectionHandler;System.Configuration.NameValueSectionHandler;不同的type不但设置配置节的方式不一样,最后访问配置文件的操作上也有差异

    在程序中如何访问这些自定义的配置节,我们用ConfigurationSettings类的静态方法GetConfig来获取自定义配置节的信息

    //访问配置节sampleSection1  
      
    IDictionary IDTest1 =(IDictionary)ConfigurationSettings.GetConfig("sampleSection1");  
      
    string str = (string)IDTest1["setting1"]+" "+(string)IDTest1["setting2"];  
      
    MessageBox.Show(str);//输出  
      
    //访问配置节sampleSection1的另一个方法
    string[] values1=new string[IDTest1.Count];  
    IDTest1.Values.CopyTo(values1,0);   
    MessageBox.Show(values1[0]+""+values1[1]); //输出
      
    //访问配置节sampleSection2  
      
    IDictionary IDTest2 =(IDictionary)ConfigurationSettings.GetConfig("sampleSection2");  
      
    string[] keys=new string[IDTest2.Keys.Count];  
      
    string[] values=new string[IDTest2.Values.Count];  
      
    IDTest2.Keys.CopyTo(keys,0);  
      
    IDTest2.Values.CopyTo(values,0);  
      
    MessageBox.Show(keys[0]+" "+values[0]); //输出 
      
    //访问配置节quartz  
      
    NameValueCollectionnc=(NameValueCollection)ConfigurationSettings.GetConfig("quartz");  
      
    MessageBox.Show(nc.AllKeys[0].ToString()+""+nc["Hello"]); //输出HelloWorld 
    配置节处理程序 返回类型
    SingleTagSectionHandler Systems.Collections.IDictionary
    DictionarySectionHandler Systems.Collections.IDictionary
    NameValueSectionHandler Systems.Collections.Specialized.NameValueCollection

    5)sectionGroup:自定义配置节组

    配置节组是使用<sectionGroup>元素,将类似的配置节分到同一个组中。配置节组声明部分将创建配置节的包含元素,在<configSections>元素中声明配置节组,并将属于该组的节置于<sectionGroup>元素中。下面是一个包含配置节组的配置文件的例子:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <sectionGroup name="TestGroup" >
          <section name="Test" type="System.Configuration.NameValueSectionHandler"/>
        </sectionGroup>
      </configSections>
      
      <TestGroup>
        <Test>
          <add key="Hello" value="World"/>
        </Test>
      </TestGroup>

    下面是访问这个配置节组的代码:

    NameValueCollectionnc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");
    
    MessageBox.Show(nc.AllKeys[0].ToString()+""+nc["Hello"]);    //输出HelloWorld



  • 相关阅读:
    Begin Example with Override Encoded SOAP XML Serialization
    State Machine Terminology
    How to: Specify an Alternate Element Name for an XML Stream
    How to: Publish Metadata for a WCF Service.(What is the Metadata Exchange Endpoint purpose.)
    Beginning Guide With Controlling XML Serialization Using Attributes(XmlSerializaiton of Array)
    Workflow 4.0 Hosting Extensions
    What can we do in the CacheMetaData Method of Activity
    How and Why to use the System.servicemodel.MessageParameterAttribute in WCF
    How to: Begin Sample with Serialization and Deserialization an Object
    A Test WCF Service without anything of config.
  • 原文地址:https://www.cnblogs.com/luna-hehe/p/9104748.html
Copyright © 2020-2023  润新知