C#中設定檔的使用

來源:互聯網
上載者:User

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

view plaincopy to clipboardprint?
  1. <?xmlversion="1.0"encoding="utf-8" ?>   
  2. <configuration>   
  3. </configuration>  

<?xmlversion="1.0"encoding="utf-8" ?><br /><configuration><br /></configuration><br />
在項目進行編譯後,在bin\Debuge檔案下,將出現兩個設定檔(以本項目為例),一個名為“JxcManagement.EXE.config”,另一個名為“JxcManagement.vshost.exe.config”。第一個檔案為項目實際使用的設定檔,在程式運行中所做的更改都將被儲存於此;第二個檔案為原代碼“app.config”的同步檔案,在程式運行中不會發生更改。
2.  connectionStrings配置節:
請注意:如果您的SQL版本為2005 Express版,則預設安裝時SQL伺服器執行個體名為localhost\SQLExpress,須更改以下執行個體中“Data Source=localhost;”一句為“Data Source=localhost\SQLExpress;”,在等號的兩邊不要加上空格。

view plaincopy to clipboardprint?
  1. <!--資料庫連接串-->   
  2.      <connectionStrings>   
  3.          <clear />   
  4.          <addname="conJxcBook"  
  5.               connectionString="Data Source=localhost;Initial Catalog=jxcbook;User                                   ID=sa;password=********"  
  6.               providerName="System.Data.SqlClient" />   
  7.      </connectionStrings>  

<!--資料庫連接串--><br /> <connectionStrings><br /> <clear /><br /> <addname="conJxcBook"<br /> connectionString="Data Source=localhost;Initial Catalog=jxcbook;User ID=sa;password=********"<br /> providerName="System.Data.SqlClient" /><br /> </connectionStrings><br />
3. appSettings配置節:
appSettings配置節為整個程式的配置,如果是對目前使用者的配置,請使用userSettings配置節,其格式與以下配置書寫要求一樣。

view plaincopy to clipboardprint?
  1. <!--進銷存管理系統初始化需要的參數-->   
  2.      <appSettings>   
  3.          <clear />   
  4.          <add key="userName" value="" />   
  5.          <add key="password" value="" />   
  6.          <add key="Department" value="" />   
  7.          <add key="returnValue" value="" />   
  8.          <add key="pwdPattern" value="" />   
  9.          <add key="userPattern" value="" />   
  10. </appSettings>  

<!--進銷存管理系統初始化需要的參數--><br /> <appSettings><br /> <clear /><br /> <addkey="userName"value="" /><br /> <addkey="password"value="" /><br /> <addkey="Department"value="" /><br /> <addkey="returnValue"value="" /><br /> <addkey="pwdPattern"value="" /><br /> <addkey="userPattern"value="" /><br /></appSettings><br />
4.讀取與更新app.config
對於app.config檔案的讀寫,參照了網路文章:http://www.codeproject.com/csharp/ SystemConfiguration.asp標題為“Read/Write App.Config File with .NET 2.0”一文。
請注意:要使用以下的代碼訪問app.config檔案,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用。
4.1 讀取connectionStrings配置節

view plaincopy to clipboardprint?
  1. ///<summary>   
  2. ///依據串連串名字connectionName返回資料連線字串   
  3. ///</summary>   
  4. ///<param name="connectionName"></param>   
  5. ///<returns></returns>   
  6. private static string GetConnectionStringsConfig(string connectionName)   
  7. {   
  8. string connectionString =    
  9.         ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();   
  10.     Console.WriteLine(connectionString);   
  11.     return connectionString;   
  12. }  

///<summary><br />///依據串連串名字connectionName返回資料連線字串<br />///</summary><br />///<param name="connectionName"></param><br />///<returns></returns><br />private static string GetConnectionStringsConfig(string connectionName)<br />{<br />string connectionString =<br /> ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();<br /> Console.WriteLine(connectionString);<br /> return connectionString;<br />}<br />
4.2 更新connectionStrings配置節

view plaincopy to clipboardprint?
  1. ///<summary>   
  2. ///更新連接字串   
  3. ///</summary>   
  4. ///<param name="newName">連接字串名稱</param>   
  5. ///<param name="newConString">連接字串內容</param>   
  6. ///<param name="newProviderName">資料提供者名稱</param>   
  7. private static void UpdateConnectionStringsConfig(string newName,   
  8.     string newConString,   
  9.     string newProviderName)   
  10. {   
  11.     bool isModified = false;    //記錄該串連串是否已經存在   
  12.     //如果要更改的串連串已經存在   
  13.     if (ConfigurationManager.ConnectionStrings[newName] != null)   
  14.     {   
  15.         isModified = true;   
  16.     }   
  17.     //建立一個連接字串執行個體   
  18.     ConnectionStringSettings mySettings =    
  19.         new ConnectionStringSettings(newName, newConString, newProviderName);   
  20.     // 開啟可執行檔設定檔*.exe.config   
  21.     Configuration config =    
  22.         ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);   
  23.     // 如果串連串已存在,首先刪除它   
  24.     if (isModified)   
  25.     {   
  26.         config.ConnectionStrings.ConnectionStrings.Remove(newName);   
  27.     }   
  28.     // 將新的串連串添加到設定檔中.   
  29.     config.ConnectionStrings.ConnectionStrings.Add(mySettings);   
  30.     // 儲存對設定檔所作的更改   
  31.     config.Save(ConfigurationSaveMode.Modified);   
  32.     // 強制重新載入設定檔的ConnectionStrings配置節   
  33.     ConfigurationManager.RefreshSection("ConnectionStrings");   
  34. }  

///<summary><br />///更新連接字串<br />///</summary><br />///<param name="newName">連接字串名稱</param><br />///<param name="newConString">連接字串內容</param><br />///<param name="newProviderName">資料提供者名稱</param><br />private static void UpdateConnectionStringsConfig(string newName,<br /> string newConString,<br /> string newProviderName)<br />{<br /> bool isModified = false; //記錄該串連串是否已經存在<br /> //如果要更改的串連串已經存在<br /> if (ConfigurationManager.ConnectionStrings[newName] != null)<br /> {<br /> isModified = true;<br /> }<br /> //建立一個連接字串執行個體<br /> ConnectionStringSettings mySettings =<br /> new ConnectionStringSettings(newName, newConString, newProviderName);<br /> // 開啟可執行檔設定檔*.exe.config<br /> Configuration config =<br /> ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);<br /> // 如果串連串已存在,首先刪除它<br /> if (isModified)<br /> {<br /> config.ConnectionStrings.ConnectionStrings.Remove(newName);<br /> }<br /> // 將新的串連串添加到設定檔中.<br /> config.ConnectionStrings.ConnectionStrings.Add(mySettings);<br /> // 儲存對設定檔所作的更改<br /> config.Save(ConfigurationSaveMode.Modified);<br /> // 強制重新載入設定檔的ConnectionStrings配置節<br /> ConfigurationManager.RefreshSection("ConnectionStrings");<br />}<br />
4.3 讀取appStrings配置節

view plaincopy to clipboardprint?
  1. ///<summary>   
  2. ///返回*.exe.config檔案中appSettings配置節的value項   
  3. ///</summary>   
  4. ///<param name="strKey"></param>   
  5. ///<returns></returns>   
  6. private static string GetAppConfig(string strKey)   
  7. {   
  8.     foreach (string key in ConfigurationManager.AppSettings)   
  9.     {   
  10.         if (key == strKey)   
  11.         {   
  12.             return ConfigurationManager.AppSettings[strKey];   
  13.         }   
  14.     }   
  15.     return null;   
  16. }  

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

view plaincopy to clipboardprint?
  1. ///<summary>   
  2. ///在*.exe.config檔案中appSettings配置節增加一對鍵、值對   
  3. ///</summary>   
  4. ///<param name="newKey"></param>   
  5. ///<param name="newValue"></param>   
  6. private static void UpdateAppConfig(string newKey, string newValue)   
  7. {   
  8.     bool isModified = false;       
  9.     foreach (string key in ConfigurationManager.AppSettings)   
  10.     {   
  11.        if(key==newKey)   
  12.         {       
  13.             isModified = true;   
  14.         }   
  15.     }   
  16.     
  17.     // Open App.Config of executable   
  18.     Configuration config =    
  19.         ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);   
  20.     // You need to remove the old settings object before you can replace it   
  21.     if (isModified)   
  22.     {   
  23.         config.AppSettings.Settings.Remove(newKey);   
  24.     }       
  25.     // Add an Application Setting.   
  26.     config.AppSettings.Settings.Add(newKey,newValue);      
  27.     // Save the changes in App.config file.   
  28.     config.Save(ConfigurationSaveMode.Modified);   
  29.     // Force a reload of a changed section.   
  30.     ConfigurationManager.RefreshSection("appSettings");   
  31. }  
  32. ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
    多層次configSections

    源地址

    http://gb2013.blog.163.com/blog/static/21735301201021253713453/

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="student" type="System.Configuration.DictionarySectionHandler"/>
      </configSections>
      <student>
        <add key="name" value="http://www.cnblogs.com/i80386/archive/2011/10/27/amily"/>
        <add key="age" value="http://www.cnblogs.com/i80386/archive/2011/10/27/15"/>
        <add key="sex" value="http://www.cnblogs.com/i80386/archive/2011/10/27/female"/>
      </student>
    </configuration>

    注意事項:configSections 相當於定義變數,必須放在configuration

                IDictionary istudent = (IDictionary)ConfigurationManager.GetSection("student");
                string[] keys=new string[istudent.Keys.Count];
                string[] values = new string[istudent.Keys.Count];

                istudent.Keys.CopyTo(keys,0);
                istudent.Values.CopyTo(values, 0);

                foreach (var key in keys)
                {
                    Console.WriteLine(key);
                }
                foreach (var value in values)
                {
                    Console.WriteLine(value);
                }

                foreach (var key in istudent.Keys)
                {
                    Console.WriteLine("{0}:{1}", key, istudent[key]);
                }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.