c# xml配置文件读取

可读取默认xml配置,没有则创建默认配置

调用方式:::

仅需要指定配置文件路径和默认配置参数

 public class Program
    {
        const string SystemConfigFile = "sys.cfg";
        static SystemConfigRead m_SystemConfigRead = new SystemConfigRead(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SystemConfigFile));
        static void Main(string[] args)
        {
            var cfg = m_SystemConfigRead.Settings;

            Console.WriteLine(cfg.DataPath);
            Console.WriteLine(cfg.Thresold);
        }

        public class SystemConfig
        {
            public string DataPath { set; get; }
            public int Thresold { set; get; }
        }

        class SystemConfigRead : BaseXmlReader<SystemConfig>
        {
            public SystemConfigRead(string filePath) : base(filePath)
            {
            }
            public override SystemConfig GetDefault()
            {
                return new SystemConfig
                {
                    DataPath = @"D:\",
                    Thresold = 100,
                };
            }
        }

}

公共代码::

 public abstract class BaseXmlReader<T> where T : class, new()
    {
        private readonly ConfigureManager<T> m_ConfigManager;
        protected readonly object s_SyncObject = new object();
        public T Settings
        {
            get
            {
                lock (s_SyncObject)
                {
                    var res = m_ConfigManager.Settings;

                    if (res == null)
                    {
                        Reset();
                    }

                    return res;
                }
            }
        }

        public event Action Updated;

        protected BaseXmlReader(string filePath)
        {
            m_ConfigManager = new ConfigureManager<T>(filePath, this);
            m_ConfigManager.Updated += ConfigChanged;
        }

        private void ConfigChanged()
        {
            Updated?.Invoke();
        }

        public virtual T GetDefault()
        {
            return null;
        }

        /// <summary>
        /// reset to default
        /// </summary>
        public virtual void Reset()
        {
            lock (s_SyncObject)
            {
                var dfg = GetDefault();
                if (dfg == null)
                {
                    dfg = Activator.CreateInstance<T>();
                }
                m_ConfigManager.Update(dfg);
            }
        }

        public virtual void Update()
        {
            lock (s_SyncObject)
            {
                m_ConfigManager.Update(Settings);
            }
        }
        public virtual void Update(T newCfg)
        {
            lock (s_SyncObject)
            {
                m_ConfigManager.Update(newCfg);
            }
        }
    }


    internal class ConfigureManager<T> where T : class, new()
    {
        private T m_CurrentSetting;

        private readonly string m_ConfigureName;

        public event Action Updated;
        readonly BaseXmlReader<T> m_reader;

        internal ConfigureManager(string fileName, BaseXmlReader<T> reader)
        {
            m_ConfigureName = fileName;
            m_reader = reader;
        }

        private T GetDefault()
        {
            return m_reader?.GetDefault();
        }

        public T Settings
        {
            get
            {
                if (m_CurrentSetting == null)
                {
                    Refresh();
                }

                return m_CurrentSetting;
            }
        }
        
        public void Update(T latest)
        {
            if (latest == null)
            {
                return;
            }
            m_CurrentSetting = latest;
            ToXmlFile(latest, m_ConfigureName);
            Updated?.Invoke();
        }

        protected virtual void Refresh()
        {
            T currentFileSetting = null;
            bool needUpdateFile = false;
            try
            {
                currentFileSetting = ObjectFromXmlFile(m_ConfigureName);
                if (currentFileSetting == null)
                {
                    currentFileSetting = GetDefault();
                    needUpdateFile = true;
                }
                if (currentFileSetting == null)
                {
                    currentFileSetting = default(T);
                    needUpdateFile = true;
                }
            }
            catch (Exception)
            {
                currentFileSetting = default(T);
                needUpdateFile = true;
            }

            if (needUpdateFile)
            {
                Update(currentFileSetting);
            }
            else
            {
                m_CurrentSetting = currentFileSetting;
            }
        }

        /// <summary>
        /// 读取序列化XML到对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path">XML文件</param>
        /// <returns>数据</returns>
        static T ObjectFromXmlFile(string path)
        {
            if (!File.Exists(path))
            {
                return null;
            }
            try
            {
                //反序列化
                using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    //返回Object类型,必须强制转换
                    return (T)GetSerializer().Deserialize(stream);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private static XmlSerializer GetSerializer()
        {
            var type = typeof(T);

            return new XmlSerializer(type);
        }

        static void ToXmlFile(T list, string path)
        {
            try
            {
                //序列化
                using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    GetSerializer().Serialize(stream, list);
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值