Asp.Net 常用工具类——Config操作(7)

.NET
399
0
0
2022-07-25
标签   ASP.NET

近期工作比较忙,忙到忘记写博客(自己的借口,主要加班下班后不想动)。

月初的时候,打算每两天写一篇博文,分享自己的一些心得和开发体验,无奈现在只写到第六篇,然而时间已经是20号,岁月不饶人!

总想写点什么,但是有时候文笔可能不咋样,排版也不是很讲究,写的碎碎的。

虽然阅读量、推荐量不高,但是我感觉做事就要持之以恒,保持分享精神

上一篇写了一些office的操作,包括excel word html pdf,现在想想,确实有点粗糙,不够精炼。

今天准备写一篇关于config文件的基本操作,包括:链接字符串,appSettings操作,运行地址等等。

大家都知道,有时候一些sdk信息账户为了可配置化,除了存库以外,webconfig的配置更能方便简介,且容易维护!

下面贴出我的帮助类(借鉴了cyqdata的帮助类,然后做了一些修改):

using System;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Reflection;
namespace Utils.Config
{
    /// <summary>  
        /// 配置文件  
        /// </summary>  
    public static class Config
    {
        /// <summary>  
            /// 配置字典  
            /// </summary>  
        public static readonly Dictionary<string, string> Configs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        /// <summary>  
            /// 链接字符串配置字典  
            /// </summary>  
        public static readonly Dictionary<string, string> ConnConfigs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        /// <summary>  
            /// 文件路径前缀  
            /// </summary>  
        public const string FilePre = "file:\\";
        /// <summary>  
            /// 框架的运行路径  
            /// </summary>  
        public static string RunfolderPath;
        /// <summary>  
            /// 框架程序集名称  
            /// </summary>  
        public static string DllFullName;
        /// <summary>  
            /// 链接字符串  
            /// </summary>  
        public static string _defaultConn;
        /// <summary>  
            /// 获取当前Dll的版本号  
            /// </summary>  
        public static string Version => Assembly.GetExecutingAssembly().GetName().Version.ToString();
        /// <summary>  
            /// Web根目录  
            /// </summary>  
        public static string WebRootPath => AppDomain.CurrentDomain.BaseDirectory;
        /// <summary>  
            /// 浏览器地址 (协议名+域名+站点名+文件名+参数)  
            /// </summary>  
        public static Uri WebUr => HttpContext.Current.Request.Url;
        /// <summary>  
            /// 框架的运行路径  
            /// </summary>  
        public static string RunFolderPath
        {
            get
            {
                if (string.IsNullOrEmpty(RunfolderPath))
                {
                    Assembly ass = Assembly.GetExecutingAssembly();
                    DllFullName = ass.FullName;
                    RunfolderPath = ass.CodeBase;
                    RunfolderPath = System.IO.Path.GetDirectoryName(RunfolderPath).Replace(FilePre, string.Empty) + "\\";
                }
                return RunfolderPath;
            }
        }
        /// <summary>  
            /// 设置Web.config或App.config的值。  
            /// </summary>  
        public static void SetApp(string key, string value)
        {
            try
            {
                if (Configs.ContainsKey(key))
                Configs[key] = value;
                else
                Configs.Add(key, value);
            }
            catch (Exception err)
            {
                Log.Log.Txt(err);
            }
        }
        /// <summary>  
            /// 获取Web.config或App.config的值。  
            /// </summary>  
        public static string GetApp(string key)
        {
            return GetApp(key, string.Empty);
        }
        /// <summary>  
            /// 获取Web.config或App.config的值(允许值不存在或为空时输出默认值)。  
            /// </summary>  
        public static string GetApp(string key, string defaultValue, string filepath = "")
        {
            if (Configs.ContainsKey(key))
                return Configs[key];
            else if (!string.IsNullOrEmpty(filepath))
            {
                ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
                ecf.ExeConfigFilename = filepath;
                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
                return config.AppSettings.Settings[key].Value;
            }
            else
            {
                string value = ConfigurationManager.AppSettings[key];
                value = string.IsNullOrEmpty(value) ? defaultValue : value;
                try
                {
                    Configs.Add(key, value);
                }
                catch (Exception err)
                {
                    Log.Log.Txt(err);
                }
                return value;
                }
        }
        /// <summary>  
            /// 获取Web.config或App.config的数字值(允许值不存在或为空时输出默认值)。  
            /// </summary>  
        public static int GetAppInt(string key, int defaultValue)
        {
            int result;
            string value = GetApp(key);
            if (!int.TryParse(value, out result))
                return defaultValue;
            return result;
        }
        /// <summary>  
            /// 获取Web.config或App.config的数字值(允许值不存在或为空时输出默认值)。  
            /// </summary>  
        public static bool GetAppBool(string key, bool defaultValue)
        {
            bool result;
            bool.TryParse(GetApp(key, defaultValue.ToString()), out result);
            return result;
        }
        /// <summary>  
            /// 获取Web.config或App.config的connectionStrings节点的值。  
            /// </summary>  
        public static string GetConn(string name, out string providerName)
        {
            providerName = string.Empty;
            if (string.IsNullOrEmpty(name))
                name = "Default";
            if (name.Trim().Contains(" "))
                return name;
            if (ConnConfigs.ContainsKey(name))
                return ConnConfigs[name];
            ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings[name];
            if (conn != null)
            {
                providerName = conn.ProviderName;
                if (name == conn.ConnectionString)//避免误写自己造成死循环。  
                    return name;
                name = conn.ConnectionString;
                if (!string.IsNullOrEmpty(name) && name.Length < 32 && name.Split(' ').Length == 1)
                    return GetConn(name);
                if (!ConnConfigs.ContainsKey(name) && string.IsNullOrEmpty(providerName)) // 如果有providerName,则不存档
                    ConnConfigs.Add(name, conn.ConnectionString);
                return conn.ConnectionString;
            }
            if (name.Length > 32 && name.Split('=').Length > 3 && name.Contains(";")) //链接字符串很长,没空格的情况  
            return name;
            return "";
        }
        /// <summary>  
            /// 获取Web.config或App.config的connectionStrings节点的值。  
            /// </summary>  
        public static string GetConn(string name)
        {
            string p;
            return GetConn(name, out p);
        }
        /// <summary>  
            /// 添加自定义链接(内存有效,并未写入config文件)  
            /// </summary>  
        /// <param name="name">名称</param>  
        /// <param name="connectionString">链接字符串</param>  
        public static void SetConn(string name, string connectionString)
        {
            if (!ConnConfigs.ContainsKey(name))
            ConnConfigs.Add(name, connectionString);
            else
            ConnConfigs[name] = connectionString;
        }
        /// <summary>  
            /// 获取URL  
            /// </summary>  
        public static string Url
        {
            get
            {
            string pageUrl = string.Empty;
            if (HttpContext.Current != null)
            {
                HttpRequest request = HttpContext.Current.Request;
                if (request.UrlReferrer != null && request.Url != request.UrlReferrer)
                    pageUrl = request.Url.Scheme + "://" + request.Url.Authority + request.RawUrl + request.UrlReferrer;
                else
                    pageUrl = request.Url.Scheme + "://" + request.Url.Authority + request.RawUrl;
            }
            return pageUrl;
            }
        }
        /// <summary>  
            /// 数据库链接字符串  
            /// </summary>  
        public static string DefaultConn
        {
            get
            {
                if (string.IsNullOrEmpty(_defaultConn))
                {
                    _defaultConn = "Defalut";
                    if (ConfigurationManager.ConnectionStrings != null && ConfigurationManager.ConnectionStrings[_defaultConn] == null)
                    {
                        foreach (ConnectionStringSettings item in ConfigurationManager.ConnectionStrings)
                        {
                            if (item.Name.ToLower().EndsWith("Defalut"))
                            {
                                _defaultConn = item.Name;
                                break;
                            }
                        }
                    }
                }
                return _defaultConn;
            }
            set
            {
                if (value == null)
                value = string.Empty;
                _defaultConn = value;
            }
        }
        /// <summary>  
            /// 生成一个文件夹路径  
            /// </summary>  
        /// <param name="foldername">文件夹名称</param>  
        /// <param name="configkey">config配置key</param>  
        public static string GenerateFilePath(string foldername, string configkey = "")
        {
            string path = GetApp(configkey, foldername);
            if (!path.EndsWith("\\"))
                path = path.TrimEnd('/');
            if (path.StartsWith("~/"))
                path = path.Substring(2);
            string folder = Config.WebRootPath;
            folder = folder + path + @"\";
            if (!System.IO.Directory.Exists(folder))
                System.IO.Directory.CreateDirectory(folder);
            return folder;
        }
    }
}

OK,各位看官,这一期的文章config操作写到这里喏,感谢大家的支持,您的支持是我的动力!

下一期给大家带来的是常用的Log帮助类,敬请期待!!!