XML - 建立屬於自己的web.config設定檔

  • 3332
  • 0
  • XML
  • 2018-04-21

本文將說明如何利用XML建立自己的設定檔,而且異動內容後不用重啟Server也可正常運行。

前言

基本上這是從某個很神奇的專案中看到的,儘管架構亂七八糟,程式碼亂七八糟,需求也談的亂七八糟,但總還是有可以記錄的東西......

這種處理法的好處是對於一些比較客製化的設定檔,像是類似物件的參數(單一參數有很多設定),或是類似陣列的資料都相對原本的Config還要更加容易的設定,同時也不用擔心臨時改參數會導致Server重啟

 

開始實作

基本上就是另外設定一個檔案作為設定的存取,因此還是需要於原本的Web.config設定檔案位置。(也可以HardCode,不過維護的人可能會覺得很幹就是)

<add key ="ExtraConfigPath" value="Config/Extra/Debug.xml"/>

以及在對應位置增加一個XML檔案

接著建立一個存取設定檔的類別,以供存取(消滅弱型別,人人有責)

using System;
using System.Configuration;
using System.Xml;
using System.IO;

namespace MvcWebApiCS.Config.Extra
{
    public static class ExtraConfig
    {
        private static string _ExtraConfigPath { get; } = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["ExtraConfigPath"] ?? "") ;
        private static DateTime _LastWriteTime { get; set; } = File.GetLastWriteTime(_ExtraConfigPath);
        private static bool _IsSame
        {
            get
            {
                var dtLastWriteTimeOld = _LastWriteTime; // Old  WriteTime
                _LastWriteTime = File.GetLastWriteTime(_ExtraConfigPath); // New WriteTime
                if (dtLastWriteTimeOld == _LastWriteTime)
                {
                    return true;
                }
                else {
                    _XmlDocument = SetXml();
                    return false;
                }
            }
        }
        private static Lazy<XmlDocument> SetXml() {
            return new Lazy<XmlDocument>(() =>
            {
                var xml = new XmlDocument();
                xml.Load(_ExtraConfigPath);
                return xml;
            });
        }
        private static Lazy<XmlDocument> _XmlDocument { get; set; } = SetXml();

        public static string ConfigKey
        {
            get
            {
                if (_ConfigKey == null || false == _IsSame)
                {
                    var xnElement = _XmlDocument.Value.SelectSingleNode("/Setting/FirstGroup/Element[@name='ConfigName']");
                    _ConfigKey = xnElement?.Attributes["value"].Value ?? "";
                }
                return _ConfigKey;
            }
        }
        private static string _ConfigKey { get; set; }


        public static string AnotherConfig
        {
            get
            {
                if (_AnotherConfig == null || false == _IsSame)
                {
                    _AnotherConfig = _XmlDocument.Value.SelectSingleNode("/Setting/FirstGroup/AnotherConfig").InnerText ?? "";
                }
                return _AnotherConfig;
            }
        }
        private static string _AnotherConfig { get; set; }
    }
}

執行結果如下(使用MVC)

中途修改參數也沒問題

 

後語

1.其實也可以用JSON格式實作....不過XML作為設定檔的可閱讀性會高一點。

2.另外也可以藉由發佈的組態檔不同特性,改變設定檔路徑,好處是可以讓不同環境的設定檔都放在版控中,往後比較好比對異動。

  <appSettings>
    <add key ="ExtraConfigPath" value="Config/Extra/Release.xml" xdt:Locator="Math(name)"/>
  </appSettings>

3.其實也有看似比較正規的作法,請參考-----> [C#] 如何在 app.config 存放「物件形式」陣列資料(https://dotblogs.com.tw/wasichris/2017/06/22/190045)

4.其實調整一下就可以當作資料儲存的載體,對於一些微型程式可直接避掉資料庫設定

參考文章

XML文件的結構 (http://irw.ncut.edu.tw/peterju/xml.html)

XmlDocument 類別 (https://msdn.microsoft.com/zh-tw/library/system.xml.xmldocument(v=vs.110).aspx)

XML 報表資料的 XML 查詢語法 (SSRS) (https://docs.microsoft.com/zh-tw/sql/reporting-services/report-data/xml-query-syntax-for-xml-report-data-ssrs)

XML命名空間(Name Space)  (http://shaocian.blogspot.tw/2013/02/xml-name-space.html)

XML Syntax Rules(https://www.w3schools.com/xml/xml_syntax.asp)

XML XPath的選擇節點語法 (http://www.hosp.ncku.edu.tw/mis/48-netdisk/57-xml-xpath.html)