App.config配置详解

经上一篇文章http://www.javashuo.com/article/p-xtfkgbul-bh.html发现本身对配置文件非常不了解,一样仍是查了半天终于发现另外一片宝贵文档http://www.javashuo.com/article/p-yllrwigh-bq.html  和 https://blog.csdn.net/z702143700/article/details/45913797 和 http://www.cnblogs.com/jhxk/articles/1609182.html(多是本身用错关键字查询);html

在此只做为本身学习记录的笔记web

  配置文件通常分为内置配置文和用户自定义配置文件。数据库

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

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

1、内置配置文件操做ide

app.config和web.config操做相似,以app.config为例,Settings.settings可以指定值的类型和范围学习

1.app.config文件操做url

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

程序移植后配置文件的修改会保存在.exe.config的文件中,可是根据我经验若是你不修改配置文件,通常exe不自动建立一个.exe.config的文件。.net

在项目进行编译后,在bin\Debuge文件下,将出现两个配置文件,一个名为“*.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");
}

须要注意的是:

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

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

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

四、可能有读者会想到,既然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
相关文章
相关标签/搜索