1. 程式人生 > WINDOWS開發 >C#架構設計-程式執行時從xml配置檔案中載入配置項並設定為全域性變數

C#架構設計-程式執行時從xml配置檔案中載入配置項並設定為全域性變數

場景

C#中全域性作用域的常量、欄位、屬性、方法的定義與使用:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102550025

在上面使用的全域性作用域的類的基礎上,如果某些設定需要儲存在某個xml配置檔案中,然後在程式啟動後從配置檔案中載入到全域性的變數中並使用。

比如:

在磁碟下某目錄中有一個xml配置檔案FileSaveCfg.xml

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

  <PreExportDataThreshold>500000</PreExportDataThreshold>

</FileSaveCfg>

那麼需要在程式執行後就載入這個配置檔案並獲取500000這個配置項,然後我

就可以在程式的任意地方通過全域性變數去獲取這個500000配置項了。

注:

部落格主頁:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程式猿
獲取程式設計相關電子書、教程推送與免費下載。

實現

為了實現程式執行後就載入配置檔案的內容,開啟專案下的Program.cs

技術分享圖片

技術分享圖片

然後在其Main方法中呼叫載入配置檔案的配置項的方法,這裡將此方法直接放在全域性Global類中,參照上面的部落格新建一個全域性Global類,類中新建Init方法,然後在上面的Main方法中呼叫Init方法

   class Program
    {
        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
  Global.Instance.Init();
        }
     }

然後來到Init方法中

        try
            {
                if (System.IO.File.Exists("d:\FileSaveCfg.xml
")) { System.Xml.XmlNode node = null; string strValue = String.Empty; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(AppConfig.TestDataDirConfigFile); node = doc.SelectSingleNode("./FileSaveCfg/PreExportDataThreshold"); if (node != null && node.FirstChild != null) { try { if (XmlHelper.GetFirstChildNodeValue(node,true,out strValue)) { int.TryParse(strValue,out Global._instance._preExportDataThreshold); } } catch (Exception ex) { Console.Write("從配置檔案{0}中解析PreExportDataThreshold異常:" + ex.Message); } } else { Console.Write("從配置檔案{0}中不包含FileSaveCfg/PreExportDataThreshold節點!"); } } } catch (Exception ex) { Console.Write("從實驗目錄所在配置檔案中解析實驗目錄異常:" + ex.Message); }

其中用到的獲取配置檔案中節點的值呼叫了一個工具類中的方法GetFirstChildNodeValue程式碼如下:

        public static bool GetFirstChildNodeValue(System.Xml.XmlNode node,bool throwException,out string value)
        {
            value = string.Empty;
            try
            {
                value = node.FirstChild.Value.ToString();
            }
            catch (Exception ex)
            {
                if (throwException)
                {
                    throw (ex);
                }
                return false;
            }
            return true;
        }

其中通過

int.TryParse(strValue,out Global._instance._preExportDataThreshold);

將從配置檔案中載入資料將其賦值給全域性欄位

Global._instance._preExportDataThreshold

在Global中定義全域性私有欄位

private int _preExportDataThreshold = 500000;

並且設定了一個預設值

然後再在Global中新增一個public的屬性,用來對私有的屬性進行讀取

        public int PreExportDataThreshold
        {
            get { return _preExportDataThreshold; }
            set { _preExportDataThreshold = value; }
        }

然後就可以在程式的任何地方通過

Global.Instance.PreExportDataThreshold

來使用從配置檔案中獲取的這個配置項了。

比如:

 if (recordDataList.Count > Global.Instance.PreExportDataThreshold )