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