c#本地文件配置xml

    /// <summary>
    /// 处理xml文件
    /// </summary>
    public class HandelXmlFile
    {
        private string _configPath;
        ///文件地址
        private void SetPath<T>()
        {
            var type = typeof(T);
            _configPath = AppDomain.CurrentDomain.BaseDirectory + @"Config\" + type.Name + ".config";
            if (!File.Exists(_configPath))
                File.Create(_configPath);
        }
        /// <summary>
        /// 保存xml文件
        /// </summary>
        public void Save<T>(T model)
        {
            try
            {
                SetPath<T>();
                using (FileStream fs = new FileStream(_configPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    XmlSerializerHelper.Serialize(fs, model);
                }
            }
            catch {  }
        }

        public T OpenFiles<T>()
        {
            try
            {
                SetPath<T>();
                if (File.Exists(_configPath))
                {
                    using (FileStream fs = new FileStream(_configPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        return XmlSerializerHelper.DeSerialize<T>(fs);
                    }
                }
                return default(T);
            }
            catch { return default(T); }
        }
    }

 

posted @ 2019-04-25 15:10  世人皆萌  阅读(688)  评论(0编辑  收藏  举报