c# winform自定義配置文件

 

1.配置文件概述: 

  應用程序配置文件是標準的 XML 文件,XML 標記和屬性是區分大小寫的。它是可以按需要更改的,開發人員可以使用配置文件來更改設置,而不必重編譯應用程序。配置文件的根節點是configuration。我們經常訪問的是appSettings,它是由.Net預定義配置節。我們經常使用的配置文件的架構是象下面的形式。先大概有個印象,通過後面的實例會有一個比較清楚的認識。下面的“配置節”可以理解爲進行配置一個XML的節點。

  常見配置文件模式:

<configuration>

        <configSections>            //配置節聲明區域,包含配置節和命名空間聲明

              <section>                          //配置節聲明

                     <sectionGroup>         //定義配置節組

                            <section>                          //配置節組中的配置節聲明

       <appSettings>                   //預定義配置節,針對整個程序的配置

       <Custom element for configuration section>        //配置節設置區域

       <userSetting>                    //針對當前用戶的配置

 

2.只有appSettings節的配置文件及訪問方法

 

  下面是一個最常見的應用程序配置文件的例子,只有appSettings節。

       <?xml version="1.0" encoding="utf-8"?>

       <configuration>

              <appSettings>

                     <add key="connectionstring" value="User ID=sa;Data Source=.;Password=;

                                                               Initial Catalog=test;Provider=SQLOLEDB.1;" />

                     <add key="TemplatePATH" value="Template" />

              </appSettings>

       </configuration>

 

  下面來看看這樣的配置文件如何讀取。

       string _connectionString=ConfigurationSettings.AppSettings["connectionstring"];

  使用ConfigurationSettings類的靜態屬性AppSettings就可以直接讀取配置文件中的配置信息。這個屬性的類型是NameValueCollection。

 

3.自定義配置文件 

 

3.1 自定義配置節

  一個用戶自定義的配置節,在配置文件中分爲兩部分:一是在<configSections></ configSections>配置節中聲明配置節(上面配置文件模式中的“<section>”),另外是在<configSections></ configSections >之後設置配置節(上面配置文件模式中的“<Custom element for configuration section>”),有點類似一個變量先聲明,後使用一樣。

  聲明一個配置文件的語句爲:<section name=" " type=" "/> 

  <section>:聲明新配置節,即可創建新配置節。

  name:自定義配置節的名稱。

  type:自定義配置節的類型,主要包括System.Configuration.SingleTagSectionHandler、System.Configuration.DictionarySectionHandler、System.Configuration.NameValueSectionHandler。

  不同的type不但設置配置節的方式不一樣,最後訪問配置文件的操作上也有差異。下面我們就舉一個配置文件的例子,讓它包含這三個不同的type。

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

       <configSections>

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

              <section name="Test2" type="System.Configuration.DictionarySectionHandler"/>

              <section name="Test3" type="System.Configuration.NameValueSectionHandler" />

       </configSections>

    

       <Test1 setting1="Hello" setting2="World"/>

       <Test2>

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

       </Test2>

       <Test3>

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

       </Test3>    

</configuration>

 

  對上面的自定義配置節進行說明。

  在聲明部分使用<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>,聲明瞭一個配置節,它的名字叫Test1,類型爲SingleTagSectionHandler;在設置配置節部分使用<Test1 setting1="Hello" setting2="World"/>設置了一個配置節,它的第一個設置的值是Hello,第二個值是World,當然還可以有更多。其它的兩個配置節和這個類似。 

  下面我們看在程序中如何訪問這些自定義的配置節。我們用過ConfigurationSettings類的靜態方法GetConfig來獲取自定義配置節的信息。

       public static object GetConfig(string sectionName);

  下面是訪問這三個配置節的代碼:

            //訪問配置節Test1

            IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig("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)ConfigurationSettings.GetConfig("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)ConfigurationSettings.GetConfig("Test3");

            MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]);    //輸出Hello World

 

  通過上面的代碼可以看出,不同的type通過GetConfig返回類型不同,具體獲得配置內容方式也不一樣。 配置節處理程序返回類型分別爲: 

       SingleTagSectionHandler   Systems.Collections.IDictionary

       DictionarySectionHandler   Systems.Collections.IDictionary

       NameValueSectionHandler   Systems.Collections.Specialized.NameValueCollection

 

3.2 自定義配置節組 

  配置節組是使用<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)ConfigurationSettings.GetConfig("TestGroup/Test");

            MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]);    //輸出Hello World

 

二.app.config/web.config的增、刪、改操作 >>>

 

  配置文件,對於程序本身來說,就是基礎和依據,其本質是一個xml文件,對於配置文件的操作,從.NET 2.0 開始,就非常方便了,提供了 System [.Web] .Configuration 這個管理功能的NameSpace,要使用它,需要添加對 System.configuration.dll的引用。 

  對於WINFORM程序,使用 System.Configuration.ConfigurationManager; 

  對於ASP.NET 程序, 使用 System.Web.Configuration.WebConfigurationManager; 

  對於配置文件內容的讀取,真是太普遍不過了,我們以最常見的 AppSettings 小節來作爲例子。假設有如下的配置文件: 

<?xml version="1.0" encoding="utf-8" ?> 

<configuration> 

       <appSettings> 

              <add key="y" value="this is Y"/> 

       </appSettings> 

</configuration> 

(注意:app.config結構與上面的結構不同,讀取方法也不一樣)

1. 讀取值

       * Asp.Net:System.Web.Configuration.WebConfigurationManager.AppSettings[“y”]; 

       * WinForm:System.Configuration.ConfigurationManager.AppSettings[“y”]; 

2. 添加一項 

       * ASP.NET(需要有寫權限):

              Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 

              AppSettingsSection app = config.AppSettings; 

              app.Settings.Add("x", "this is X"); 

              config.Save(ConfigurationSaveMode.Modified); 

       * WinForm:

              Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

              AppSettingsSection app = config.AppSettings; 

              app.Settings.Add("x", "this is X"); 

              config.Save(ConfigurationSaveMode.Modified); 

3. 修改一項 

       * Asp.Net:

              Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 

              AppSettingsSection app = config.AppSettings; 

              //app.Settings.Add("x", "this is X"); 

              app.Settings["x"].Value = "this is not Y"; 

              config.Save(ConfigurationSaveMode.Modified); 

       * WinForm:

              Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

              AppSettingsSection app = config.AppSettings; 

              //app.Settings.Add("x", "this is X"); 

              app.Settings["x"].Value = "this is not Y"; 

              config.Save(ConfigurationSaveMode.Modified); 

4. 刪除一項 

       * Asp.Net:

              Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 

              AppSettingsSection app = config.AppSettings; 

              app.Settings.Remove("x"); 

              config.Save(ConfigurationSaveMode.Modified); 

       * WinForm:

              Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

              AppSettingsSection app = config.AppSettings; 

              app.Settings.Remove("x"); 

              config.Save(ConfigurationSaveMode.Modified);



三.上機操作[vs2005] >>>



1.向項目添加app.config文件: 

  右擊項目名稱,選擇“添加”→“添加新建項”,在出現的“添加新項”對話框中,選擇“添加應用程序配置文件”;如果項目以前沒有配置文件,則默認的文件名稱爲“app.config”,單擊“確定”。出現在設計器視圖中的app.config文件爲: 

  <?xmlversion="1.0"encoding="utf-8" ?> 

  <configuration> 

  </configuration> 

  在項目進行編譯後,在bin/Debuge文件下,將出現兩個配置文件(以本項目爲例),一個名爲“XXX.EXE.config”,另一個名爲“XXX.vshost.exe.config”。第一個文件爲項目實際使用的配置文件,在程序運行中所做的更改都將被保存於此;第二個文件爲原代碼“app.config”的同步文件,在程序運行中不會發生更改。 

 

2.connectionStrings配置節: 

  請注意:如果您的SQL版本爲2005 Express版,則默認安裝時SQL服務器實例名爲localhost/SQLExpress,須更改以下實例中“Data Source=localhost;”一句爲“Data Source=localhost/SQLExpress;”,在等於號的兩邊不要加上空格。 

  <!--數據庫連接串--> 

  <connectionStrings> 

          <clear /> 

          <add 

connectionString="Data Source=localhost;Initial Catalog=jxcbook;

                      User ID=sa;password=********" 

provider /> 

  </connectionStrings> 

 

3.appSettings配置節: 

  appSettings配置節爲整個程序的配置,如果是對當前用戶的配置,請使用userSettings配置節,其格式與以下配置書寫要求一樣。 

  <!--進銷存管理系統初始化需要的參數--> 

  <appSettings> 

  <clear /> 

  <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> 

 

4.讀取與更新app.config 

  對於app.config文件的讀寫,參照“Read/Write App.Config File with .NET 2.0”一文

【點我進入

。 

  請注意:要使用以下的代碼訪問app.config文件,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用。 

 

4.1 讀取connectionStrings配置節 

  ///<summary> 

  ///依據連接串名字connectionName返回數據連接字符串 

  ///</summary> 

  private static string GetConnectionStringsConfig(string connectionName) 

  { 

              string connectionString = 

                        ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString(); 

              Console.WriteLine(connectionString); 

              return connectionString; 

       } 

4.2 更新connectionStrings配置節 

  ///<summary> 

  ///更新連接字符串 

  ///</summary> 

  ///<param >連接字符串名稱</param> 

  ///<param >連接字符串內容</param> 

  ///<param >數據提供程序名稱</param> 

  private static void UpdateConnectionStringsConfig

                                          (string newName, string newConString, string newProviderName) 

  { 

         bool isModified = false;             //記錄該連接串是否已經存在 

         //如果要更改的連接串已經存在 

         if (ConfigurationManager.ConnectionStrings[newName] != null) 

         { 

                isModified = true; 

            } 

          //新建一個連接字符串實例 

          ConnectionStringSettings mySettings = 

          new ConnectionStringSettings(newName, newConString, newProviderName); 

          // 打開可執行的配置文件*.exe.config 

          Configuration config = 

                               ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

          // 如果連接串已存在,首先刪除它 

          if (isModified) 

          { 

                 config.ConnectionStrings.ConnectionStrings.Remove( newName); 

          } 

          // 將新的連接串添加到配置文件中. 

          config.ConnectionStrings.ConnectionStrings.Add(mySettings); 

          // 保存對配置文件所作的更改 

          config.Save(ConfigurationSaveMode.Modified); 

          // 強制重新載入配置文件的ConnectionStrings配置節 

          ConfigurationManager.RefreshSection("connectionStrings"); 

  } 

 

4.3 讀取appStrings配置節 

  ///<summary> 

  ///返回*.exe.config文件中appSettings配置節的value項 

  ///</summary> 

  private static string GetAppConfig(string strKey) 

  { 

          foreach (string key in ConfigurationManager.AppSettings) 

          { 

                 if (key == strKey) 

                 { 

                        return ConfigurationManager.AppSettings[strKey]; 

                 } 

          } 

          return null; 

  } 

 

4.4 更新connectionStrings配置節 

  ///<summary> 

  ///在*.exe.config文件中appSettings配置節增加一對鍵、值對 

  ///</summary> 

  private static void UpdateAppConfig(string newKey, string newValue) 

  { 

          bool isModified = false; 

          foreach (string key in ConfigurationManager.AppSettings) 

          { 

                 if(key==newKey) 

                 { 

                        isModified = true; 

                 } 

          } 

          // Open App.Config of executable 

          Configuration config = 

                               ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

          // You need to remove the old settings object before you can replace it 

          if (isModified) 

          { 

                 config.AppSettings.Settings.Remove(newKey); 

          } 

          // Add an Application Setting. 

          config.AppSettings.Settings.Add(newKey,newValue); 

          // Save the changes in App.config file. 

          config.Save(ConfigurationSaveMode.Modified); 

          // Force a reload of a changed section. 

          ConfigurationManager.RefreshSection("appSettings") ; 

  } 

 

5.加密配置文件 

  此節代碼參照Dariush Tasdighi所著文章《Encrypt and Decrypt of ConnectionString in app.config and/or web.config!》【點我進入】。 

  請注意:(1)要使用以下的代碼訪問app.config文件,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用; (2)以下示例代碼中的DPAPI提供程序爲“DataProtectionConfigurationProvider”,這是一種基於機器名和當前用戶密碼的加密方式。如果計劃在多臺服務器(Web 場合)上使用相同的加密配置文件,則只有通過 RSAProtectedConfigurationProvider 才能導出加密密鑰,並將其導入其他服務器。(3)加密後的配置文件不需要解密即可用上述方法直接讀取。 

 

5.1 加密connectionStrings配置節 

  ///<summary> 

  ///加密配置文件中的ConnectionString節 

  ///</summary> 

  ///<param >true爲加密,false爲解密</param> 

  public static void ConnectionStringProtection( bool protect) 

  { 

          //取得當前程序的執行路徑 

          string pathName = Application.ExecutablePath; 

          // 定義Dpapi提供程序的名稱. 

          string strProvider = "DataProtectionConfigurationProvider"; 

          System.Configuration.Configuration oConfiguration = null; 

          System.Configuration.ConnectionStringsSection oSection = null; 

          try 

          { 

                 // 打開配置文件,並取得connectionStrings配置節. 

                 oConfiguration = 

                               System.Configuration.ConfigurationManager.OpenExeConfiguration(

<param>

true爲加密,false爲解密</param> );

                 public static void AppSettingProtection(bool protect) 

                 { 

                        //取得當前程序的執行路徑 

                        string pathName = Application.ExecutablePath; 

                        // Define the Dpapi provider name. 

                        string strProvider = "DataProtectionConfigurationProvider"; 

                        System.Configuration.Configuration oConfiguration = null; 

                        System.Configuration.AppSettingsSection oSection = null; 

                        try 

                        { 

                               // Open the configuration file and retrieve the connectionStrings section. 

                               oConfiguration = 

                                             System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName); 

                               if (oConfiguration != null) 

                               { 

                                      bool blnChanged = false; 

                                      oSection = oConfiguration.GetSection("appSettings") as 

                                                                                System.Configuration.AppSettingsSection; 

                                      if (oSection != null) 

                                      { 

                                             if ((!(oSection.ElementInformation.IsLocked)) 

                                                                         &&(!(oSection.SectionInformation.IsLocked))) 

                                             { 

                                                    if (protect) 

                                                    { 

                                                           if (!(oSection.SectionInformation.IsProtected)) 

                                                           { 

                                                                  blnChanged = true; 

                                                                  // Encrypt the section. 

                                                                  oSection.SectionInformation.ProtectSection(strProv ider); 

                                                           } 

                                                    } 

                                                    else 

                                                    { 

                                                           if (oSection.SectionInformation.IsProtected) 

                                                           { 

                                                                  blnChanged = true; 

                                                                  // Remove encryption. 

                                                                  oSection.SectionInformation.UnprotectSection(); 

                                                           } 

                                                    } 

                                             } 

                                             if (blnChanged) 

                                             { 

                                                    // Indicates whether the associated configuration section will be saved even 

                                                    // if it has not been modified. 

                                                    oSection.SectionInformation.ForceSave = true; 

                                                    // Save the current configuration. 

                                                    oConfiguration.Save(); 

                                               } 

                                      } 

                               } 

                        } 

                        catch (System.Exception ex) 

                        { 

                               throw (ex); 

                        } 

                     }

          finally 

          { 

          } 

     } 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章