C#知识点总结

这是我在开发了这几年的时间中,总结出来一些知识点,个人感觉一边开发一边总结真的是一个非常好的习惯,特别有助于个人技术的提高……

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Text.RegularExpressions;

namespace Common
{
    public class Validate
    {
        private static readonly Regex RegPhone = 
        new Regex("(^(\\d{11})$|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)");  //电话号码和手机验证
        private static Regex RegEmail = new Regex("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@([\\w-]+\\.)+\\w{2,3})\\s*$"); //w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
        private static Regex RegNum = new Regex("^[0-9]+$");

        //必须是数字正则表达式(小数或整数)
        private static Regex regex = new Regex(@"/^[0-9]+\.?[0-9]{0,3}$/");
        /// <summary>
        /// 身份证正值表达式
        /// </summary>
        private static readonly Regex RegCardId = new Regex("(^\\d{15}$)|(^\\d{17}([0-9]|X|x)$)");
        
        #region 确定用户输入是否合法
        /// <summary>
        /// 确定用户输入是否合法
        /// </summary>
        /// <param name="text">用户输入字符串</param>
        /// <param name="maxLength">最大字符串长度</param>
        /// <returns></returns>
        public static string InputText(string text, int maxLength)
        {
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            text = text.Trim();
            if (maxLength != 0)
                if (text.Length > maxLength)
                    text = text.Substring(0, maxLength);
            text = Regex.Replace(text, "[\\s]{2,}", " ");
            text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");
            text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");
            //text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //屏蔽标签
            text = text.Replace("'", "''");
            return text;
        }
        #endregion

        #region 验证电话号码
        // 电话号码和手机号码检查
        /// <summary>
        /// 电话号码和手机号码检查
        /// </summary>
        /// <param name="inputData">电话号码或手机号码</param>
        /// <returns>匹配结果</returns>
        public static bool IsPhone(string inputData)
        {
            Match m = RegPhone.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 验证参数是否为中文字符
        /// <summary>
        /// 验证参数是否为中文字符
        /// </summary>
        /// <param name="input">输入参数</param>
        /// <returns></returns>
        public static bool IsChinese(string input)
        {
            Regex regex = new Regex(@"[\u4e00-\u9fa5]", RegexOptions.IgnoreCase);
            return regex.IsMatch(input);
        }
        #endregion

        #region 邮件地址

        /// <summary>
        /// 邮件地址验证
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns>验证结果</returns>
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 是否为数字
        /// <summary>
        /// 是否为数字
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns>是否为数字</returns>
        public static bool IsNum(string inputData)
        {
            if(string.IsNullOrEmpty(inputData))
            {
                return false;
            }
            Match m = RegNum.Match(inputData);
            return m.Success;
        }
        /// <summary>
        /// 判断是否是整数或小数
        /// </summary>
        /// <param name="str">输入的字符串</param>
        /// <returns>是否为数字</returns>
        public static bool IsNumAll(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return false;
            }
            Match m = regex.Match(str);
            return m.Success;
        }

        #endregion

        #region 是否为身份证
        /// <summary>
        /// 是否为身份证
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns>是否为身份证</returns>
        public static bool IsCardId(string inputData)
        {
            Match m = RegCardId.Match(inputData);
            return m.Success;
        }
        #endregion


        /// <summary>
        /// 判断字符串是否是纯数字
        /// </summary>
        /// <param name="message">源字符串</param>
        /// <returns></returns>
        public static bool IsNumberic(string message)//, out int result
        {
            System.Text.RegularExpressions.Regex rex =
            new System.Text.RegularExpressions.Regex(@"^\d+$");
            var result = -1;
            if (rex.IsMatch(message))
            {
                result = int.Parse(message);
                return true;
            }
            else
                return false;
        }
        
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="number">截取多少位</param>
        /// <param name="str">原字符串</param>
        /// <returns></returns>
        public static string InterceptionBytes(int number, string str)
        {
            //4*6  24 -2  22*2=44  44ge 字节  43
            if (str == null)
                return "";
            var result = new StringBuilder();
            var count = 0;
            if (Encoding.GetEncoding("GB2312").GetByteCount(str) <= number)
            {
                return str;
            }
            foreach (char t in str)
            {
                if (Encoding.GetEncoding("GB2312").GetByteCount(new[] { t }) == 2)
                {
                    count += 2;
                    result.Append(t);
                }
                else if (Encoding.GetEncoding("GB2312").GetByteCount(new[] { t }) == 1)
                {

                    count += 1;
                    result.Append(t);
                }
                else
                {
                    count += 3;
                    result.Append(t);
                }
                if (count >= (number - 2))
                    break;
            }
            result.Append("...");
            return result.ToString();
        }
        
        /// <summary>
        /// 返回指定位数的随机密码(数字和字母的组合)
        /// </summary>
        /// <param name="median">密码位数(非负数)</param>
        /// <returns>string</returns>
        public static string GetPassword(int median)
        {
            Random ra = new Random();
            string str = "";
            string newstr = "";
            int l1 = median / 3;
            int l2 = median / 3;
            int l3 = median / 3 + median % 3;

            int[] lower = new int[l1];//小写字母
            int[] upper = new int[l2];//大写字母
            int[] num = new int[l3]; //数字

            byte[] bs1 = new byte[l1]; //存放小写字母
            byte[] bs2 = new byte[l2]; //存放大写字母

            Encoding en = Encoding.Default;

            #region //初始化随机数和字母
            for (int i = 0; i < lower.Length; i++)
            {
                lower[i] = ra.Next(65, 91);
                bs1[i] = byte.Parse(lower[i].ToString());
            }
            for (int j = 0; j < upper.Length; j++)
            {
                upper[j] = ra.Next(97, 123);
                bs2[j] = byte.Parse(upper[j].ToString());
            }
            for (int k = 0; k < num.Length; k++)
            {
                num[k] = ra.Next(0, 10);
            }
            #endregion

            string tempnum = num.Aggregate("", (current, t) => current + t);
            //拼接成临时字符串,方便按照下标取值
            str += en.GetString(bs1) + en.GetString(bs2) + tempnum;

            List<string> li = new List<string>();
            for (int a = 0; a < str.Length; a++)
            {
                li.Insert(a, str[a].ToString());
            }

            while (li.Count != 0)
            {
                var count = ra.Next(0, li.Count);
                newstr += li[count];
                li.RemoveAt(count);
            }

            return newstr;
        }
        
        /// <summary>  
        /// 加密处理  
        /// </summary>  
        /// <param name="Input"></param>  
        /// <returns></returns>  
        public static string Encrypt(string Input)
        {
            try
            {
                var des = new DESCryptoServiceProvider();
                var inputByteArray = Encoding.UTF8.GetBytes(Input);
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateEncryptor(Key, Iv), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception)
            {
                return "";
            }
        }
        
        /// <summary>  
        /// 解密处理  
        /// </summary>  
        /// <param name="Input"></param>  
        /// <returns></returns>  
        public static string Decrypt(string Input)
        {
            if (!string.IsNullOrEmpty(Input))
            {
                Input = Input.Replace(" ", "+");
                try
                {
                    var des = new DESCryptoServiceProvider();
                    var inputByteArray = Convert.FromBase64String(Input);
                    var ms = new MemoryStream();
                    var cs = new CryptoStream(ms, des.CreateDecryptor(Key, Iv), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    var encoding = Encoding.UTF8;
                    return encoding.GetString(ms.ToArray());
                }
                catch (Exception)
                {
                    return "";
                }
            }
            return "";
        }
        
        #region 全角半角转换
        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>全角字符串</returns>
        ///<remarks>
        ///全角空格为12288,半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
        ///</remarks>
        public static string ToSBC(string input)
        {
            //半角转全角:
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }
        /// <summary> 转半角的函数(DBC case) </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>半角字符串</returns>
        ///<remarks>
        ///全角空格为12288,半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
        ///</remarks>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        #endregion
        
        /// <summary>
        /// 返回全路徑文件名稱
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetValidateFileName(string folderPath, string fileName)
        {           
            string result = string.Empty;
            DirectoryInfo di = new DirectoryInfo(folderPath);
            FileInfo[] files = di.GetFiles(fileName);
            if (files.Any())
            {
                result = files[0].FullName;
            }
            return result;
        }
        
        #region 获取时间戳  
        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }
        #endregion 
        
        ///獲取隨機數
        public static int RandomInteger(int min, int max)
        {
            RNGCryptoServiceProvider Rand = new RNGCryptoServiceProvider();
            uint scale = uint.MaxValue;
            while (scale == uint.MaxValue)
            {
                // Get four random bytes.
                byte[] four_bytes = new byte[4];
                Rand.GetBytes(four_bytes);

                // Convert that into an uint.
                scale = BitConverter.ToUInt32(four_bytes, 0);
            }

            // Add min to the scaled difference between max and min.
            return (int)(min + (max - min) *
                (scale / (double)uint.MaxValue));
        }
    }
}

 

转载于:https://www.cnblogs.com/Mr-Worlf/p/8709256.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值