码迷,mamicode.com
首页 > Windows程序 > 详细

C#共用工具类

时间:2020-04-13 00:30:07      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:获得   options   cond   引号   encoding   return   ase   ram   当前日期   

using System;
using System.Text;
using System.Text.RegularExpressions;

namespace Utilities
{
///


/// 共用工具类
///

public static class Tools
{
#region 得到字符串长度,一个汉字长度为2
///
/// 得到字符串长度,一个汉字长度为2
///

/// 参数字符串
///
public static int StrLength(string inputString)
{
System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
int tempLen = 0;
byte[] s = ascii.GetBytes(inputString);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
tempLen += 2;
else
tempLen += 1;
}
return tempLen;
}
#endregion

    #region 截取指定长度字符串
    /// <summary>
    /// 截取指定长度字符串
    /// </summary>
    /// <param name="inputString">要处理的字符串</param>
    /// <param name="len">指定长度</param>
    /// <returns>返回处理后的字符串</returns>
    public static string ClipString(string inputString, int len)
    {
        bool isShowFix = false;
        if (len % 2 == 1)
        {
            isShowFix = true;
            len--;
        }
        System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
        int tempLen = 0;
        string tempString = "";
        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
                tempLen += 2;
            else
                tempLen += 1;

            try
            {
                tempString += inputString.Substring(i, 1);
            }
            catch
            {
                break;
            }

            if (tempLen > len)
                break;
        }

        byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
        if (isShowFix && mybyte.Length > len)
            tempString += "…";
        return tempString;
    }
    #endregion

    #region 获得两个日期的间隔
    /// <summary>
    /// 获得两个日期的间隔
    /// </summary>
    /// <param name="DateTime1">日期一。</param>
    /// <param name="DateTime2">日期二。</param>
    /// <returns>日期间隔TimeSpan。</returns>
    public static TimeSpan DateDiff(DateTime DateTime1, DateTime DateTime2)
    {
        TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
        TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
        TimeSpan ts = ts1.Subtract(ts2).Duration();
        return ts;
    }
    #endregion

    #region 格式化日期时间
    /// <summary>
    /// 格式化日期时间
    /// </summary>
    /// <param name="dateTime1">日期时间</param>
    /// <param name="dateMode">显示模式</param>
    /// <returns>0-9种模式的日期</returns>
    public static string FormatDate(DateTime dateTime1, string dateMode)
    {
        switch (dateMode)
        {
            case "0":
                return dateTime1.ToString("yyyy-MM-dd");
            case "1":
                return dateTime1.ToString("yyyy-MM-dd HH:mm:ss");
            case "2":
                return dateTime1.ToString("yyyy/MM/dd");
            case "3":
                return dateTime1.ToString("yyyy年MM月dd日");
            case "4":
                return dateTime1.ToString("MM-dd");
            case "5":
                return dateTime1.ToString("MM/dd");
            case "6":
                return dateTime1.ToString("MM月dd日");
            case "7":
                return dateTime1.ToString("yyyy-MM");
            case "8":
                return dateTime1.ToString("yyyy/MM");
            case "9":
                return dateTime1.ToString("yyyy年MM月");
            default:
                return dateTime1.ToString();
        }
    }
    #endregion

    #region 得到随机日期
    /// <summary>
    /// 得到随机日期
    /// </summary>
    /// <param name="time1">起始日期</param>
    /// <param name="time2">结束日期</param>
    /// <returns>间隔日期之间的 随机日期</returns>
    public static DateTime GetRandomTime(DateTime time1, DateTime time2)
    {
        Random random = new Random();
        DateTime minTime = new DateTime();
        DateTime maxTime = new DateTime();

        System.TimeSpan ts = new System.TimeSpan(time1.Ticks - time2.Ticks);

        // 获取两个时间相隔的秒数
        double dTotalSecontds = ts.TotalSeconds;
        int iTotalSecontds = 0;

        if (dTotalSecontds > System.Int32.MaxValue)
        {
            iTotalSecontds = System.Int32.MaxValue;
        }
        else if (dTotalSecontds < System.Int32.MinValue)
        {
            iTotalSecontds = System.Int32.MinValue;
        }
        else
        {
            iTotalSecontds = (int)dTotalSecontds;
        }


        if (iTotalSecontds > 0)
        {
            minTime = time2;
            maxTime = time1;
        }
        else if (iTotalSecontds < 0)
        {
            minTime = time1;
            maxTime = time2;
        }
        else
        {
            return time1;
        }

        int maxValue = iTotalSecontds;

        if (iTotalSecontds <= System.Int32.MinValue)
            maxValue = System.Int32.MinValue + 1;

        int i = random.Next(System.Math.Abs(maxValue));

        return minTime.AddSeconds(i);
    }
    #endregion

    #region 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;
    }
    #endregion

    #region 判断对象是否为空
    /// <summary>
    /// 判断对象是否为空,为空返回true
    /// </summary>
    /// <typeparam name="T">要验证的对象的类型</typeparam>
    /// <param name="data">要验证的对象</param>        
    public static bool IsNullOrEmpty<T>(T data)
    {
        //如果为null
        if (data == null)
        {
            return true;
        }

        //如果为""
        if (data.GetType() == typeof(String))
        {
            if (string.IsNullOrEmpty(data.ToString().Trim()))
            {
                return true;
            }
        }

        //如果为DBNull
        if (data.GetType() == typeof(DBNull))
        {
            return true;
        }

        //不为空
        return false;
    }

    /// <summary>
    /// 判断对象是否为空,为空返回true
    /// </summary>
    /// <param name="data">要验证的对象</param>
    public static bool IsNullOrEmpty(object data)
    {
        //如果为null
        if (data == null)
        {
            return true;
        }

        //如果为""
        if (data.GetType() == typeof(String))
        {
            if (string.IsNullOrEmpty(data.ToString().Trim()))
            {
                return true;
            }
        }

        //如果为DBNull
        if (data.GetType() == typeof(DBNull))
        {
            return true;
        }

        //不为空
        return false;
    }
    #endregion

    #region 验证IP地址是否合法
    /// <summary>
    /// 验证IP地址是否合法
    /// </summary>
    /// <param name="ip">要验证的IP地址</param>        
    public static bool IsIP(string ip)
    {
        string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
        Regex RegexHelper = new Regex(pattern);
        //如果为空,认为验证合格
        if (IsNullOrEmpty(ip))
        {
            return true;
        }

        //清除要验证字符串中的空格
        ip = ip.Trim();

        //模式字符串
       

        //验证
        return RegexHelper.IsMatch(ip);
    }
    #endregion

    #region  验证EMail是否合法
    /// <summary>
    /// 验证EMail是否合法
    /// </summary>
    /// <param name="email">要验证的Email</param>
    public static bool IsEmail(string email)
    {
        //如果为空,认为验证不合格
        if (IsNullOrEmpty(email))
        {
            return false;
        }

        //清除要验证字符串中的空格
        email = email.Trim();

        //模式字符串
        string pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
        Regex RegexHelper = new Regex(pattern);
        //验证
        return RegexHelper.IsMatch(email);
    }
    #endregion

    #region 验证是否为整数
    /// <summary>
    /// 验证是否为整数 如果为空,认为验证不合格 返回false
    /// </summary>
    /// <param name="number">要验证的整数</param>        
    public static bool IsInt(string number)
    {
        //如果为空,认为验证不合格
        if (IsNullOrEmpty(number))
        {
            return false;
        }

        //清除要验证字符串中的空格
        number = number.Trim();

        //模式字符串
        string pattern = @"^[0-9]+[0-9]*$";
        Regex RegexHelper = new Regex(pattern);
        //验证
        return RegexHelper.IsMatch(number);
    }
    #endregion

    #region 验证是否为数字
    /// <summary>
    /// 验证是否为数字
    /// </summary>
    /// <param name="number">要验证的数字</param>        
    public static bool IsNumber(string number)
    {
        //如果为空,认为验证不合格
        if (IsNullOrEmpty(number))
        {
            return false;
        }

        //清除要验证字符串中的空格
        number = number.Trim();

        //模式字符串
        string pattern = @"^[0-9]+[0-9]*[.]?[0-9]*$";
        Regex RegexHelper = new Regex(pattern);
        //验证
        return RegexHelper.IsMatch(number);
    }
    #endregion

    #region 验证日期是否合法
    /// <summary>
    /// 验证日期是否合法,对不规则的作了简单处理
    /// </summary>
    /// <param name="date">日期</param>
    public static bool IsDate(ref string date)
    {
        //如果为空,认为验证合格
        if (IsNullOrEmpty(date))
        {
            return true;
        }

        //清除要验证字符串中的空格
        date = date.Trim();

        //替换        date = date.Replace(@"\", "-");
        //替换/
        date = date.Replace(@"/", "-");

        //如果查找到汉字"今",则认为是当前日期
        if (date.IndexOf("今") != -1)
        {
            date = DateTime.Now.ToString();
        }

        try
        {
            //用转换测试是否为规则的日期字符
            date = Convert.ToDateTime(date).ToString("d");
            return true;
        }
        catch
        {
            //如果日期字符串中存在非数字,则返回false
            if (!IsInt(date))
            {
                return false;
            }

            #region 对纯数字进行解析
            //对8位纯数字进行解析
            if (date.Length == 8)
            {
                //获取年月日
                string year = date.Substring(0, 4);
                string month = date.Substring(4, 2);
                string day = date.Substring(6, 2);

                //验证合法性
                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }
                if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31)
                {
                    return false;
                }

                //拼接日期
                date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");
                return true;
            }

            //对6位纯数字进行解析
            if (date.Length == 6)
            {
                //获取年月
                string year = date.Substring(0, 4);
                string month = date.Substring(4, 2);

                //验证合法性
                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }
                if (Convert.ToInt32(month) > 12)
                {
                    return false;
                }

                //拼接日期
                date = Convert.ToDateTime(year + "-" + month).ToString("d");
                return true;
            }

            //对5位纯数字进行解析
            if (date.Length == 5)
            {
                //获取年月
                string year = date.Substring(0, 4);
                string month = date.Substring(4, 1);

                //验证合法性
                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }

                //拼接日期
                date = year + "-" + month;
                return true;
            }

            //对4位纯数字进行解析
            if (date.Length == 4)
            {
                //获取年
                string year = date.Substring(0, 4);

                //验证合法性
                if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100)
                {
                    return false;
                }

                //拼接日期
                date = Convert.ToDateTime(year).ToString("d");
                return true;
            }
            #endregion

            return false;
        }
    }
    #endregion

    #region 验证身份证是否合法
    /// <summary>
    /// 验证身份证是否合法
    /// </summary>
    /// <param name="idCard">要验证的身份证</param>        
    public static bool IsIdCard(string idCard)
    {
        //如果为空,认为验证合格
        if (IsNullOrEmpty(idCard))
        {
            return true;
        }

        //清除要验证字符串中的空格
        idCard = idCard.Trim();

        //模式字符串
        StringBuilder pattern = new StringBuilder();
        pattern.Append(@"^(11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|");
        pattern.Append(@"50|51|52|53|54|61|62|63|64|65|71|81|82|91)");
        pattern.Append(@"(\d{13}|\d{15}[\dx])$");
        Regex RegexHelper = new Regex(pattern.ToString());
        //验证
        return RegexHelper.IsMatch(idCard);
    }
    #endregion

    #region 检测客户的输入中是否有危险字符串
    /// <summary>
    /// 检测客户输入的字符串是否有效,并将原始字符串修改为有效字符串或空字符串。
    /// 当检测到客户的输入中有攻击性危险字符串,则返回false,有效返回true。
    /// </summary>
    /// <param name="input">要检测的字符串</param>
    public static bool IsValidInput(ref string input)
    {
        try
        {
            if (IsNullOrEmpty(input))
            {
                //如果是空值,则跳出
                return true;
            }
            else
            {
                //替换单引号
                input = input.Replace("‘", "").Trim();

                //检测攻击性危险字符串
                string testString = "and |or |exec |insert |select |delete |update |count |chr |mid |master |truncate |char |declare ";
                string[] testArray = testString.Split(‘|‘);
                foreach (string testStr in testArray)
                {
                    if (input.ToLower().IndexOf(testStr) != -1)
                    {
                        //检测到攻击字符串,清空传入的值
                        input = "";
                        return false;
                    }
                }

                //未检测到攻击字符串
                return true;
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }
    #endregion
}

}

C#共用工具类

标签:获得   options   cond   引号   encoding   return   ase   ram   当前日期   

原文地址:https://www.cnblogs.com/zhujie-com/p/12688779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!