C#項目中如何讀取並修改App.config檔案

來源:互聯網
上載者:User

本文簡單介紹C#項目中讀取並修改App.config檔案的方法,AppConfig最重要的功能就是它將命令列選項和設定檔選項統一到一種資料結構中。

1. 向C#項目執行個體中的項目添加app.config檔案:

右擊C#項目執行個體中項目名稱,選擇“添加”→“添加建立項”,在出現的“添加新項”對話方塊中,選擇“添加應用程式設定檔”;如果項目以前沒有設定檔,則預設的檔案名稱為“app.config”,單擊“確定”。出現在設計器視圖中的app.config檔案為:

<?xmlversionxmlversionxmlversionxmlversion="1.0"encoding="utf-8" ?>     <configuration>     </configuration>

在項目進行編譯後,在binDebuge檔案下,將出現兩個設定檔(以本項目為例),一個名為“***.EXE.config”,另一個名為“***.vshost.exe.config”。第一個檔案為項目實際使用的設定檔,在程式運行中所做的更改都將被儲存於此;第二個檔案為原代碼“app.config”的同步檔案,在程式運行中不會發生更改.

2.  SQL 2005 ExpressconnectionStrings配置:

注意:等號的兩邊不要加上空格。

<connectionStrings>              <addnameaddname="***Name"                connectionString="Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=********"                providerName="System.Data.SqlClient"  />     </connectionStrings>

3. appSettings/userSetting 配置節:

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

<appSettings>              <clear  />              <addkeyaddkeyaddkeyaddkey="userName"value=""  />              <addkeyaddkeyaddkeyaddkey="password"value=""  />     </appSettings>

4.讀取與更新app.config

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

(1) 讀取connectionStrings配置節

///<summary>     ///依據串連串名字connectionName返回資料連線字串      ///</summary>     ///<param name="connectionName"></param>     ///<returns></returns>     private static string GetConnectionStringsConfig(string connectionName)      {              string connectionString =               ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();                         return connectionString;      }

(2) 更新connectionStrings配置節

///<summary>     ///更新連接字串      ///</summary>     ///<param name="newName">連接字串名稱</param>     ///<param name="newConString">連接字串內容</param>///查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp////<param name="newProviderName">資料提供者名稱</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");      }

(3)讀取appStrings配置節

///<summary>     ///返回***.exe.config檔案中appSettings配置節的value項      ///</summary>     ///<param name="strKey"></param>     ///<returns></returns>     private static string GetAppConfig(string strKey)      {          foreach (string key in ConfigurationManager.AppSettings)          {              if (key == strKey)              {                  return ConfigurationManager.AppSettings[strKey];              }          }          return null;      }

(4) 更新connectionStrings配置節

///<summary>      ///在***.exe.config檔案中appSettings配置節增加一對鍵、值對      ///</summary>      ///<param name="newKey"></param>      ///<param name="newValue"></param>      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");      }

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.