当前位置: 首页 > news >正文

asp.net——公共帮助类

在项目开发中公共帮助类是必不可少的,这里记录一些自己摘录或自己编写的帮助类。

64位编码与解码:

 #region URL的64位编码
        /// <summary>
        /// URL的64位编码
        /// </summary>
        /// <param name="sourthUrl"></param>
        /// <returns></returns>
        public static string Base64Encrypt(string sourthUrl)
        {
            string eurl = HttpUtility.UrlEncode(sourthUrl);
            eurl = Convert.ToBase64String(Encoding.Default.GetBytes(eurl));
            return eurl;
        }
        #endregion

        #region URL的64位解码 
        /// <summary>
        /// URL的64位解码 
        /// </summary>
        /// <param name="eStr"></param>
        /// <returns></returns>
        public static string Base64Decrypt(string eStr)
        {
            if (!IsBase64(eStr))
            {
                return eStr;
            }
            byte[] buffer = Convert.FromBase64String(eStr);
            string sourthUrl = Encoding.Default.GetString(buffer);
            sourthUrl = HttpUtility.UrlDecode(sourthUrl);
            return sourthUrl;
        }
        #endregion  

        #region 检查一个字符串是否是Base64字符串
        /// <summary>
        /// 检查一个字符串是否是Base64字符串
        /// </summary>
        /// <param name="eStr"></param>
        /// <returns></returns>
        public static bool IsBase64(string eStr)
        {
            if ((eStr.Length % 4) != 0)
            {
                return false;
            }
            if (!Regex.IsMatch(eStr, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
            {
                return false;
            }
            return true;
        }
        #endregion
View Code

字符串过滤:

 #region 检测是否有Sql危险字符
        /// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        /// <summary>
        /// 检查危险字符
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string Filter(string sInput)
        {
            if (sInput == null || sInput == "")
                return null;
            string sInput1 = sInput.ToLower();
            string output = sInput;
            string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
            if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
            {
                throw new Exception("字符串中含有非法字符!");
            }
            else
            {
                output = output.Replace("'", "''");
            }
            return output;
        }

        /// <summary> 
        /// 检查过滤设定的危险字符
        /// </summary> 
        /// <param name="InText">要过滤的字符串 </param> 
        /// <returns>如果参数存在不安全字符,则返回true </returns> 
        public static bool SqlFilter(string word, string InText)
        {
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 过滤特殊字符
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string Htmls(string Input)
        {
            if (Input != string.Empty && Input != null)
            {
                string ihtml = Input.ToLower();
                ihtml = ihtml.Replace("<script", "&lt;script");
                ihtml = ihtml.Replace("script>", "script&gt;");
                ihtml = ihtml.Replace("<%", "&lt;%");
                ihtml = ihtml.Replace("%>", "%&gt;");
                ihtml = ihtml.Replace("<$", "&lt;$");
                ihtml = ihtml.Replace("$>", "$&gt;");
                return ihtml;
            }
            else
            {
                return string.Empty;
            }
        }
        #endregion
View Code

字符串与List相互转化:

        #region 把字符串按照分隔符转换成 List
        /// <summary>
        /// 把字符串按照分隔符转换成 List
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="speater">分隔符</param>
        /// <param name="toLower">是否转换为小写</param>
        /// <returns></returns>
        public static List<string> GetStrArray(string str, char speater, bool toLower)
        {
            List<string> list = new List<string>();
            string[] ss = str.Split(speater);
            foreach (string s in ss)
            {
                if (!string.IsNullOrEmpty(s) && s != speater.ToString())
                {
                    string strVal = s;
                    if (toLower)
                    {
                        strVal = s.ToLower();
                    }
                    list.Add(strVal);
                }
            }
            return list;
        }
        #endregion

        #region 把 List<string> 按照分隔符组装成 string
        /// <summary>
        /// 把 List<string> 按照分隔符组装成 string
        /// </summary>
        /// <param name="list"></param>
        /// <param name="speater">分隔符</param>
        /// <returns></returns>
        public static string GetArrayStr(List<string> list, string speater)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sb.Append(list[i]);
                }
                else
                {
                    sb.Append(list[i]);
                    sb.Append(speater);
                }
            }
            return sb.ToString();
        }
        #endregion

        #region 把 List<int> 按照分隔符组装成 string
        /// <summary>
        /// 把 List<int> 按照分隔符组装成 string
        /// </summary>
        /// <param name="list"></param>
        /// <param name="speater">分隔符</param>
        /// <returns></returns>
        public static string GetArrayStr(List<int> list, string speater)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sb.Append(list[i].ToString());
                }
                else
                {
                    sb.Append(list[i]);
                    sb.Append(",");
                }
            }
            return sb.ToString();
        }
        #endregion
View Code

HTML转成Text文本:

/// <summary>
        /// HTML转行成TEXT
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string HtmlToTxt(string strHtml)
        {
            string[] aryReg ={
            @"<script[^>]*?>.*?</script>",
            @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
            @"([\r\n])[\s]+",
            @"&(quot|#34);",
            @"&(amp|#38);",
            @"&(lt|#60);",
            @"&(gt|#62);",
            @"&(nbsp|#160);",
            @"&(iexcl|#161);",
            @"&(cent|#162);",
            @"&(pound|#163);",
            @"&(copy|#169);",
            @"&#(\d+);",
            @"-->",
            @"<!--.*\n"
            };

            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, string.Empty);
            }

            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");


            return strOutput;
        }
View Code

DataTable转List<T>:

 /// <summary>
        ///  DataTable转换成List<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="IsDataField"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt, bool IsDataField) where T : new()
        {
            List<T> ts = new List<T>();
            Type type = typeof(T);
            string tempName = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                T myt = new T();
                PropertyInfo[] propertys = myt.GetType().GetProperties();
                PropertyInfo[] array = propertys;
                int i = 0;
                DataFieldAttribute attribute = null;
                PropertyAttribute proAttribute = null;
                while (i < array.Length)
                {
                    PropertyInfo pi = array[i];
                    if (IsDataField)
                    {
                        object[] infos = null;
                        object[] pros = null;
                        infos = pi.GetCustomAttributes(typeof(DataFieldAttribute), false);
                        pros = pi.GetCustomAttributes(typeof(PropertyAttribute), false);
                        if (infos.Length > 0)
                        {
                            attribute = (DataFieldAttribute)(infos[0]);
                            if (pros.Length > 0)
                            {
                                proAttribute = (PropertyAttribute)(pros[0]);
                                if (proAttribute.columnKeyType != ColumnKeyType.Extend)
                                {
                                    tempName = attribute.FieldName;
                                }
                            }
                            else
                                tempName = attribute.FieldName;
                        }
                    }
                    else
                        tempName = pi.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (pi.CanWrite)
                        {
                            object value = dr[tempName];
                            //if (value.GetType().Equals(typeof(DateTime)))
                            //    value = System.Convert.ToString(value);
                            if (value != DBNull.Value)
                                pi.SetValue(myt, value, null);
                        }
                    }
                    i += 1;
                    continue;
                }
                ts.Add(myt);
            }
            return ts;
        }
View Code

DataTable 转 Object:

/// <summary>
        /// DataTable 转 Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static T DataTableToObject<T>(DataTable dt, bool IsDataField) where T : new()
        {
            Type type = typeof(T);
            string tempName = string.Empty;
            T myt = new T();
            PropertyInfo[] propertys = myt.GetType().GetProperties();
            PropertyInfo[] array = propertys;
            int i = 0;
            DataFieldAttribute attribute = null;
            PropertyAttribute proAttribute = null;
            while (i < array.Length)
            {
                PropertyInfo pi = array[i];
                if (IsDataField)
                {
                    object[] infos = null;
                    object[] pros = null;
                    infos = pi.GetCustomAttributes(typeof(DataFieldAttribute), false);
                    pros = pi.GetCustomAttributes(typeof(PropertyAttribute), false);
                    if (infos.Length > 0)
                    {
                        attribute = (DataFieldAttribute)(infos[0]);
                        if (pros.Length>0)
                        {
                            proAttribute = (PropertyAttribute)(pros[0]);
                            if (proAttribute.columnKeyType != ColumnKeyType.Extend)
                            {
                                tempName = attribute.FieldName;
                            }
                        }else
                            tempName = attribute.FieldName;
                    }
                }
                else
                    tempName = pi.Name;

                if (dt.Columns.Contains(tempName))
                {
                    if (pi.CanWrite)
                    {
                        object value = dt.Rows[0][tempName];
                        //if (value.GetType().Equals(typeof(DateTime)))
                        //    value = Convert.ToString(value);
                        if (value != DBNull.Value)
                            pi.SetValue(myt, value, null);
                    }
                }
                i += 1;
                continue;
            }
            return myt;
        }
View Code

CacheHelper:

/// <summary>
        /// 获取数据缓存
        /// </summary>
        /// <param name="CacheKey"></param>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
        }

        /// <summary>
        /// 设置数据缓存
        /// </summary>
        public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
        }

        /// <summary>
        /// 移除指定数据缓存
        /// </summary>
        public static void RemoveAllCache(string CacheKey)
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            _cache.Remove(CacheKey);
        }

        /// <summary>
        /// 移除全部缓存
        /// </summary>
        public static void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                _cache.Remove(CacheEnum.Key.ToString());
            }
        }
View Code

 

 

转载于:https://www.cnblogs.com/witeem/p/5594615.html

相关文章:

  • 什么是二次开发
  • C++ 解析json串
  • 系统管理员需知的 16 个 iptables 使用技巧
  • $Django python中使用redis, django中使用(封装了),redis开启事务(管道)
  • 《HelloGitHub》第 33 期
  • grep-学习记录
  • 面试题30:包含 min 函数的栈
  • intellij中导入java包
  • Java模仿http请求工具类
  • 数据结构之链表 给定一个链表,判断链表中是否有环。
  • 有点颓废
  • JS判断单、多张图片加载完成
  • webfont在vue中的使用
  • DS树+图综合练习--二叉树之最大路径
  • cf954H
  • $translatePartialLoader加载失败及解决方式
  • 〔开发系列〕一次关于小程序开发的深度总结
  • 08.Android之View事件问题
  • Akka系列(七):Actor持久化之Akka persistence
  • css选择器
  • Idea+maven+scala构建包并在spark on yarn 运行
  • JavaScript实现分页效果
  • k个最大的数及变种小结
  • MySQL的数据类型
  • Redis提升并发能力 | 从0开始构建SpringCloud微服务(2)
  • SpiderData 2019年2月16日 DApp数据排行榜
  • vue+element后台管理系统,从后端获取路由表,并正常渲染
  • vue-loader 源码解析系列之 selector
  • 彻底搞懂浏览器Event-loop
  • 工作踩坑系列——https访问遇到“已阻止载入混合活动内容”
  • 人脸识别最新开发经验demo
  • 使用parted解决大于2T的磁盘分区
  • 王永庆:技术创新改变教育未来
  • 微信小程序设置上一页数据
  • 小李飞刀:SQL题目刷起来!
  • 一道面试题引发的“血案”
  • 应用生命周期终极 DevOps 工具包
  • Java性能优化之JVM GC(垃圾回收机制)
  • 曜石科技宣布获得千万级天使轮投资,全方面布局电竞产业链 ...
  • ​io --- 处理流的核心工具​
  • #Z0458. 树的中心2
  • ( 用例图)定义了系统的功能需求,它是从系统的外部看系统功能,并不描述系统内部对功能的具体实现
  • (10)ATF MMU转换表
  • (八)五种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (附源码)ssm高校志愿者服务系统 毕业设计 011648
  • (规划)24届春招和25届暑假实习路线准备规划
  • (离散数学)逻辑连接词
  • (篇九)MySQL常用内置函数
  • (一)kafka实战——kafka源码编译启动
  • (一)Mocha源码阅读: 项目结构及命令行启动
  • (一)spring cloud微服务分布式云架构 - Spring Cloud简介
  • (转)c++ std::pair 与 std::make
  • * 论文笔记 【Wide Deep Learning for Recommender Systems】
  • ***原理与防范
  • .Net 4.0并行库实用性演练