重拾C#日常積累:config設定檔的讀寫

來源:互聯網
上載者:User

注;現在FrameWork2.0以上使用的是:ConfigurationManager或WebConfigurationManager。並且AppSettings屬性是唯讀,並不支援修改屬性值.文章參考了網上一些內容進行整理輸出。 一、設定檔的說明

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

常見設定檔模式:

<configuration>                      // 頂層配置節
<configSections>                    //配置節聲明地區,包含配置節和命名空間聲明
<section>                         //配置節聲明
<sectionGroup>                //定義配置節組
<section>                        //配置節組中的配置節聲明
<appSettings>                       //預定義配置節
<Custom element for configuration section>   //配置節設定地區

下面是一個最常見的應用程式設定檔的例子,只有appSettings節:

<?xml version="1.0" encoding="utf-8"?><configuration>    <appSettings>        <add key="connectionstring" value="User Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" />        <add key="TemplatePATH" value="Template" />    </appSettings></configuration>    
注意:在預定義的 appSettings 節(注意大小寫),有很多的元素,這些元素名稱都是“add”,有兩個屬性分別是“key”和“value”。

二、如何使用ConfigurationManager。 1、添加引用:添加System.configguration

2、引用空間

3、App.config設定檔配置節

常用配置節:

(1)普通配置節

<appSettings>    <add key="COM1" value="COM1,9600,8,None,1,已啟用" /></appSettings> 

(2)資料來源配置節

<connectionStrings>  <add name="kyd" connectionString="server=.;database=UFDATA_999_2017;user=sa;pwd=123"/></connectionStrings>

(3)自訂配置節

4、擷取配置的方式

樣本:

(1)、AppSettings

https://msdn.microsoft.com/zh-cn/library/system.configuration.configurationmanager.appsettings(v=vs.110).aspx


  //系統自訂Key首碼public static readonly string SysCustomKey = ConfigurationManager.AppSettings["redisKey"] ?? "";

(2)、ConnectionStrings

https://msdn.microsoft.com/zh-cn/library/system.configuration.configurationmanager.connectionstrings(v=vs.110).aspx


 private static readonly string RedisConnectionString = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString;

三、App.config設定檔讀寫 1、依據串連串名字connectionName返回資料連線字串 
        //依據串連串名字connectionName返回資料連線字串          public static string GetConnectionStringsConfig(string connectionName)        {            //指定config檔案讀取            string file = System.Windows.Forms.Application.ExecutablePath;            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file);            string connectionString =                config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();            return connectionString;        }
2、更新連接字串
        ///<summary>         ///更新連接字串          ///</summary>         ///<param name="newName">連接字串名稱</param>         ///<param name="newConString">連接字串內容</param>         ///<param name="newProviderName">資料提供者名稱</param>         public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)        {            //指定config檔案讀取            string file = System.Windows.Forms.Application.ExecutablePath;            Configuration config = ConfigurationManager.OpenExeConfiguration(file);            bool exist = false; //記錄該串連串是否已經存在              //如果要更改的串連串已經存在              if (config.ConnectionStrings.ConnectionStrings[newName] != null)            {                exist = true;            }            // 如果串連串已存在,首先刪除它              if (exist)            {                config.ConnectionStrings.ConnectionStrings.Remove(newName);            }            //建立一個連接字串執行個體              ConnectionStringSettings mySettings =                new ConnectionStringSettings(newName, newConString, newProviderName);            // 將新的串連串添加到設定檔中.              config.ConnectionStrings.ConnectionStrings.Add(mySettings);            // 儲存對設定檔所作的更改              config.Save(ConfigurationSaveMode.Modified);            // 強制重新載入設定檔的ConnectionStrings配置節              ConfigurationManager.RefreshSection("connectionStrings");        }
3、返回*.exe.config檔案中appSettings配置節的value項 
        ///<summary>         ///返回*.exe.config檔案中appSettings配置節的value項          ///</summary>         ///<param name="strKey"></param>         ///<returns></returns>         public static string GetAppConfig(string strKey)        {            string file = System.Windows.Forms.Application.ExecutablePath;            Configuration config = ConfigurationManager.OpenExeConfiguration(file);            foreach (string key in config.AppSettings.Settings.AllKeys)            {                if (key == strKey)                {                    return config.AppSettings.Settings[strKey].Value.ToString();                }            }            return null;        }
4、在*.exe.config檔案中appSettings配置節增加一對索引值對 
        ///<summary>          ///在*.exe.config檔案中appSettings配置節增加一對索引值對          ///</summary>          ///<param name="newKey"></param>          ///<param name="newValue"></param>          public static void UpdateAppConfig(string newKey, string newValue)        {            string file = System.Windows.Forms.Application.ExecutablePath;            Configuration config = ConfigurationManager.OpenExeConfiguration(file);            bool exist = false;            foreach (string key in config.AppSettings.Settings.AllKeys)            {                if (key == newKey)                {                    exist = true;                }            }            if (exist)            {                config.AppSettings.Settings.Remove(newKey);            }            config.AppSettings.Settings.Add(newKey, newValue);            config.Save(ConfigurationSaveMode.Modified);            ConfigurationManager.RefreshSection("appSettings");        }
5、config讀取
using System.Configuration;//省略其他代碼public SalesOrderData()        {            string str = "";            str = ConfigurationManager.ConnectionStrings["kyd"].ToString();            conn = new SqlConnection(str);            cmd = conn.CreateCommand();        }
6、重設修改值


7、儲存修改值


四、快速實現讀寫設定檔

這裡以key、value進行操作為例:

    using System;      using System.Collections.Generic;      using System.Text;      using System.Configuration;            namespace BoonyaTests      {          /// <summary>          /// 對exe.Config檔案中的appSettings段進行讀寫配置操作          /// 注意:調試時,寫操作將寫在vhost.exe.config檔案中          /// </summary>          public class ConfigAppSettings          {              /// <summary>              /// 寫入值              /// </summary>              /// <param name="key"></param>              /// <param name="value"></param>              public static void SetValue(string key, string value)              {                  //增加的內容寫在appSettings段下 <add key="RegCode" value="0"/>                  System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);                  if (config.AppSettings.Settings[key] == null)                  {                      config.AppSettings.Settings.Add(key, value);                  }                  else                  {                      config.AppSettings.Settings[key].Value = value;                  }                  config.Save(ConfigurationSaveMode.Modified);                  ConfigurationManager.RefreshSection("appSettings");//重新載入新的設定檔               }                    /// <summary>              /// 讀取指定key的值              /// </summary>              /// <param name="key"></param>              /// <returns></returns>              public static string GetValue(string key)              {                   System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);                  if (config.AppSettings.Settings[key] == null)                      return "";                  else                      return config.AppSettings.Settings[key].Value;              }                }      }     

參考文章:

https://www.cnblogs.com/qq450867541/p/7119433.html

https://www.cnblogs.com/feiyuhuo/p/5243967.html

https://www.cnblogs.com/lgx5/p/7353690.html

聯繫我們

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