DOGNET

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace DogNet.Common.AppConfig

{

     /// <summary>
    /// Xml配置文件加载,监听
    /// </summary>

    public class XmlFileConfig
    {
        private string _fullPath;
        private object _lockObject;
        private XDocument _xmlDocument;

        #region 构造函数
        public XmlFileConfig(string path, string name)
        {
            this._fullPath = Path.Combine(path, name);
            this._lockObject = new object();

            // 添加监视
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.Filter = name;
            watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;
            watcher.Changed += new FileSystemEventHandler(WatchHandler_OnChanged);
            watcher.EnableRaisingEvents = true;
        }
        #endregion

        public XDocument XmlDocument
        {
            get
            {
                if (_xmlDocument == null)
                {
                    lock (_lockObject)
                    {
                        if (_xmlDocument == null)
                        {
                            this._xmlDocument = LoadConfig();
                        }
                    }
                }
                return _xmlDocument;
            }
        }

        private XDocument LoadConfig()
        {
            try
            {
                return XDocument.Load(this._fullPath);
            }
            catch
            {
                return this._xmlDocument;
            }
        }

        private void WatchHandler_OnChanged(object source, FileSystemEventArgs e)
        {            
            lock (this._lockObject)
            {
                this._xmlDocument = LoadConfig();
            }
        }
    }
}
posted on 2010-05-18 10:32  DOGNET  阅读(357)  评论(0编辑  收藏  举报