• C#应用程序配置文件.config介绍


    我们经常会希望在程序中写入一些配置信息,例如版本号,以及数据库的连接字符串等。你可能知道在WinForm应用程序中可以利用Properties.Settings来进行类似的工作,但这些其实都利用了App.config配置文件。本文探讨用代码的方式访问 App.config 的方法

    1. 配置文件概述: 
    应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置文件的根节点是configuration。我们经常访问的是appSettings,它是由.Net预定义配置节。我们经常使用的配置文件的架构是象下面的形式。先大概有个印象,通过后面的实例会有一个比较清楚的认识。下面的“配置节”可以理解为进行配置一个XML的节点。

    常见配置文件模式:

    <configuration>
    <configSections>     //配置节声明区域,包含配置节和命名空间声明
    <section>            //配置节声明
    <sectionGroup>       //定义配置节组
       <section>         //配置节组中的配置节声明
    <appSettings>        //预定义配置节
    <Custom element for configuration section>  //配置节设置区域

    2. config配置文件配置节

    (1)普通配置节

      <appSettings>
        <add key="ConnStr1" value="User ID=sa;Data Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" />
      </appSettings>

    (2)数据源配置节

      <connectionStrings>
        <add name="ConnStr2" connectionString="LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;Initial Catalog=aspnetdb" providerName="System.Data.SqlClient" />
      </connectionStrings>

    完整如下

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <appSettings>
        <add key="ConnStr1" value="User ID=sa;Data Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" />
      </appSettings>
    
      <connectionStrings>
        <add name="ConnStr2" connectionString="LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;Initial Catalog=aspnetdb"
          providerName="System.Data.SqlClient" />
      </connectionStrings>
    </configuration>

    下面来看看这样的配置文件如何访问

    ①添加引用 System.Configuration

    ②引入命名空间

    using System.Configuration;
    string _connStr1 = ConfigurationManager.AppSettings["ConnStr1"];
    string _connStr2 = ConfigurationManager.ConnectionStrings["ConnStr2"].ToString();         

    (3)自定义配置节   一个用户自定义的配置节,在配置文件中分为两部分:

    首先在<configSections></ configSections>配置节中声明配置节(上面配置文件模式中的“<section>”)

     <configSections>
          <section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>      
     </configSections>

    然后是在<configSections></ configSections >之后设置配置节(上面配置文件模式中的“<Custom element for configuration section>”),有点类似一个变量先声明,后使用一样。

    <Test1>
         <add key="Hello" value="World" />
    </Test1>

    声明一个配置文件的语句如下:

    <section name=" " type=" "/> 
    section:声明新配置节,即可创建新配置节。
    name:   自定义配置节的名称。
    type:   自定义配置节的类型,主要包括System.Configuration.SingleTagSectionHandler、System.Configuration.DictionarySectionHandler、System.Configuration.NameValueSectionHandler。

    不同的type不但设置配置节的方式不一样,最后访问配置文件的操作上也有差异。

    type的类型有许多,参见 System.Configuration 命名空间

    下面我们就举一个配置文件的例子,让它包含这三个不同的type。

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <!--声明了一个配置节它的名字叫Test1,类型为SingleTagSectionHandler-->
            <section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>
            <section name="Test2" type="System.Configuration.DictionarySectionHandler"/>
            <section name="Test3" type="System.Configuration.NameValueSectionHandler" />
        </configSections>
        
        <!--设置了一个配置节,它的第一个设置的值是Hello,第二个值是World,当然还可以有更多-->
        <Test1 setting1="Hello" setting2="World"/>
        <Test2>
            <add key="Hello" value="World" />
        </Test2>
        <Test3>
            <add key="Hello" value="World" />
        </Test3>    
    </configuration>

    下面我们看在程序中如何访问这些自定义的配置节。

    我们通过ConfigurationManager类的静态方法GetSection来获取自定义配置节的信息。

    using System.Configuration;
    using System.Collections;
    using System.Collections.Specialized;
    
            //访问配置节Test1
            IDictionary IDTest1 = (IDictionary)ConfigurationManager.GetSection("Test1");
            string str = (string)IDTest1["setting1"] + " " + (string)IDTest1["setting2"];
            MessageBox.Show(str);                              //输出Hello World
    
            //访问配置节Test1的方法2
            string[] values1 = new string[IDTest1.Count];
            IDTest1.Values.CopyTo(values1, 0);
            MessageBox.Show(values1[0] + " " + values1[1]);    //输出Hello World
    
            //访问配置节Test2
            IDictionary IDTest2 = (IDictionary)ConfigurationManager.GetSection("Test2");
            string[] keys = new string[IDTest2.Keys.Count];
            string[] values = new string[IDTest2.Keys.Count];
            IDTest2.Keys.CopyTo(keys, 0);
            IDTest2.Values.CopyTo(values, 0);
            MessageBox.Show(keys[0] + " " + values[0]);
    
            //访问配置节Test3
            NameValueCollection nc = (NameValueCollection)ConfigurationManager.GetSection("Test3");
            MessageBox.Show(nc.AllKeys[0].ToString() + " " + nc["Hello"]);    //输出Hello World

    通过上面的代码我们可以看出,不同的type通过GetConfig返回的类型不同,具体获得配置内容的方式也不一样。 

    配置节处理程序返回类型

    SingleTagSectionHandler
    System.Collections.IDictionary
    
    DictionarySectionHandler
    System.Collections.IDictionary
    
    NameValueSectionHandler
    System.Collections.Specialized.NameValueCollection

     3 自定义配置节组 
    配置节组是使用<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>
    </configuration>


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

    NameValueCollection nc = (NameValueCollection)ConfigurationManager.GetSection("TestGroup/Test");
    MessageBox.Show(nc.AllKeys[0].ToString() + " " + nc["Hello"]);    //输出Hello World

    4.appSettings配置节的读写操作

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

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

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

    //获取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 = "cnblogs";
    //增加<add>元素
    config.AppSettings.Settings.Add("url", "http://www.cnblogs.com");
    //删除<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、在项目进行编译后,在运行目录binDebuge文件下,将出现两个配置文件,一个名为“ProjectName.EXE.config”,另一个名为“ProjectName.vshost.exe.config”。第一个文件为项目实际使用的配置文件,在程序运行中所做的更改都将被保存于此;第二个文件其实为原代码中“App.config”的同步文件,在程序运行中不会发生更改。

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

    5、可能有读者会想到,既然app.config是标准XML,当然也可以用操纵一般XML文件的方法来读写。这当然是可以的!具体可以看文末参考文献[2]和[3]中的代码,只不过我认为这样就失去了VS提供app.config文件的意义了,还不如自己定义一个配置文件方便。

    本文只是粗略地讲了app.config文件中appSettings配置节的访问方法,connectionStrings配置节的操作基本是类似的,也可以自定义配置节。这些高级的用法可以自己体会,VS对app.config这个配置文件的管理还是很强大的,例如WinForm应用程序的Settings设置(可以在IDE中或者通过代码访问)其实也是利用了app.config文件。

     
    参考

    [1]C# winform 自定义应用程序配置文件(app.config)

    [2]C#读写App.config配置文件的方法

    [3]在.net中读写config文件的各种方法 (文章内容挺多的,还没仔细看)

  • 相关阅读:
    命令行添加subl命令
    mac 本地跨域
    ionic2 处理android硬件返回按钮
    ionic2 (真正)修改应用图标和启动画面
    ionic2 隐藏滚动条
    Tomcat在Eclips中的使用及注意细节
    JAVA解析xml的四种方式比较
    程序人生咖啡馆
    浅谈JAVA中HashMap、ArrayList、StringBuilder等的扩容机制
    mySQL 的 2个分类
  • 原文地址:https://www.cnblogs.com/code1992/p/9242809.html
Copyright © 2020-2023  润新知