ConfigHelper 配置文件辅助类

简介:
using System;
using System.Globalization;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Helper
{
    /// <summary>
    ///     配置文件辅助类
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        ///     更新配置信息,将配置信息对象序列化至相应的配置文件中,文件格式为带签名的UTF-8
        /// </summary>
        /// <typeparam name="T">配置信息类</typeparam>
        /// <param name="config">配置信息</param>
        public static void UpdateConfig<T>(T config)
        {
            Type configClassType = typeof (T);
            string configFilePath = GetConfigPath<T>(); //根据配置文件名读取配置文件  
            try
            {
                var xmlSerializer = new XmlSerializer(configClassType);
                using (var xmlTextWriter = new XmlTextWriter(configFilePath, Encoding.UTF8))
                {
                    xmlTextWriter.Formatting = Formatting.Indented;
                    var xmlNamespace = new XmlSerializerNamespaces();
                    xmlNamespace.Add(string.Empty, string.Empty);
                    xmlSerializer.Serialize(xmlTextWriter, config, xmlNamespace);
                }
            }
            catch (SecurityException ex)
            {
                throw new SecurityException(ex.Message, ex.DenySetInstance, ex.PermitOnlySetInstance, ex.Method,
                                            ex.Demanded, ex.FirstPermissionThatFailed);
            }
        }


        /// <summary>
        ///     获取配置信息
        /// </summary>
        /// <typeparam name="T">配置信息类</typeparam>
        /// <returns>配置信息</returns>
        public static T GetConfig<T>() where T : class, new()
        {
            var configObject = new object();
            Type configClassType = typeof (T);
            string configFilePath = GetConfigPath<T>(); //根据配置文件名读取配置文件  
            if (File.Exists(configFilePath))
            {
                using (var xmlTextReader = new XmlTextReader(configFilePath))
                {
                    var xmlSerializer = new XmlSerializer(configClassType);
                    configObject = xmlSerializer.Deserialize(xmlTextReader);
                }
            }
            var config = configObject as T;
            if (config == null)
            {
                return new T();
            }
            return config;
        }

        /// <summary>
        ///     获取配置文件的服务器物理文件路径
        /// </summary>
        /// <typeparam name="T">配置信息类</typeparam>
        /// <returns>配置文件路径</returns>
        public static string GetConfigPath<T>()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            if (path == AppDomain.CurrentDomain.BaseDirectory)
            {
                path = path + typeof (T).Name + ".config";
            }
            return path;
        }


        public static string GetDirPath(string dirName)
        {
            string dirPath = dirName;
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            return dirPath;
        }

        public static string Md5(string input)
        {
            using (var md5 = new MD5CryptoServiceProvider())
            {
                byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                return BitConverter.ToString(data).Replace("-", string.Empty).ToLower(CultureInfo.CurrentCulture);
            }
        }

        /// <summary>
        ///     读取配置文件
        /// </summary>
        /// <returns></returns>
        public static string ReadConfig<T>()
        {
            string configContent = string.Empty;
            string filePath = GetConfigPath<T>();
            if (File.Exists(filePath))
            {
                using (var sr = new StreamReader(filePath, Encoding.Default))
                {
                    configContent = sr.ReadToEnd();
                    sr.Close();
                }
            }
            return configContent;
        }

        /// <summary>
        ///     写入配置文件
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public static void WriteConfig<T>(string config)
        {
            string fileName = GetConfigPath<T>();
            using (StreamWriter w = File.AppendText(fileName))
            {
                w.WriteLine(config);
                w.Close();
            }
        }
    }
}

目录
相关文章
|
4月前
|
前端开发
Bootstrap辅助类
【10月更文挑战第21天】
34 3
|
Java 容器 Spring
实现EnvironmentAware接口 将配置文件中的属性放置到系统环境变量中
实现EnvironmentAware接口 将配置文件中的属性放置到系统环境变量中
355 31
|
Java 数据库连接 数据库
MyBatis核心配置文件结构及核心配置文件标签详解
MyBatis核心配置文件结构及核心配置文件标签详解
183 0
|
Java 测试技术 数据库连接
springboot原理实战(6)--配置文件注入集合,动态注入,切换profile环境
springboot原理实战(6)--配置文件注入集合,动态注入,切换profile环境
379 0
springboot原理实战(6)--配置文件注入集合,动态注入,切换profile环境
|
运维 Kubernetes 安全
DO447使用过滤器和插件转换器--使用查找模板化外部数据
DO447使用过滤器和插件转换器--使用查找模板化外部数据
261 1
DO447使用过滤器和插件转换器--使用查找模板化外部数据
直接取配置文件对应数据映射到对象中,可在代码中直接使用
直接取配置文件对应数据映射到对象中,可在代码中直接使用
|
XML 存储 缓存
Spring源码解析——Bean加载(doCreateBean方法补充)
本文接这上一篇:520就应该和女朋友一起学习Spring源码——Bean加载 对其进行补充~