首页 > 代码库 > .net工具类

.net工具类

ConvertHelper

技术分享
public class ConvertHelper
    {
        /// <summary>
        /// 转换类型
        /// </summary>
        /// <typeparam name="T">要转换的类型,可以为Nullable的泛型</typeparam>
        /// <param name="val">要转换的值</param>
        /// <returns></returns>
        public static T ConvertType<T>(object val)
        {
            return ConvertType<T>(val, default(T));
        }

        /// <summary>
        /// 转换类型
        /// </summary>
        /// <typeparam name="T">要转换的类型,可以为Nullable的泛型</typeparam>
        /// <param name="val">要转换的值</param>
        /// <param name="defaultVal">转换失败默认的值</param>
        /// <returns></returns>
        public static T ConvertType<T>(object val, T defaultVal)
        {
            object returnVal = ConvertByType(val, typeof(T));
            if (returnVal == null)
                return defaultVal;
            else
            {
                return (T)returnVal;
            }
        }

        /// <summary>
        /// 通过反射获取未知类型时的类型转换
        /// 转换失败返回null
        /// </summary>
        /// <param name="val"></param>
        /// <param name="tp"></param>
        /// <returns></returns>
        public static object ConvertByType(object val, Type tp)
        {
            if (val == null) return null;
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            #region 单独转换Datetime和String

            if (tp.Name.ToLower() == "datetime")
            {
                DateTime? dt = ParseDateTime(val.ToString());
                if (dt == null) return null;
                object objDt = dt.Value;
                return objDt;
            }
            if (tp.Name.ToLower() == "string")
            {
                object objStr = val.ToString();
                return objStr;
            }
            #endregion
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { val.ToString(), Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                return parameters[1];
            }
            return null;
        }

        /// <summary>
        /// 转换类型,返回是否转换成功
        /// </summary>
        /// <typeparam name="T">要转换的类型</typeparam>
        /// <param name="val">要转换的值</param>
        /// <param name="returnVal">返回的值</param>
        /// <returns></returns>
        public static bool TryConvert<T>(object val, out T returnVal)
        {
            returnVal = default(T);
            if (val == null) return false;
            Type tp = typeof(T);
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }

            #region 单独转换Datetime和string

            if (tp.Name.ToLower() == "datetime")
            {
                DateTime? dt = ParseDateTime(val.ToString());
                if (dt == null) return false;
                object objDt = dt.Value;
                returnVal = (T)objDt;
                return true;
            }
            if (tp.Name.ToLower() == "string")
            {
                object objStr = val.ToString();
                returnVal = (T)objStr;
                return true;
            }
            #endregion

            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { val.ToString(), Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                returnVal = (T)parameters[1];
                return true;
            }
            return false;
        }

        /// <summary>
        /// 转换为DateTime
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <returns></returns>
        public static DateTime ConvertToDateTime(object obj, DateTime defaultValue)
        {
            DateTime result = defaultValue;
            if (obj != null)
            {
                if (!DateTime.TryParse(obj.ToString().Trim(), out result))
                {
                    result = defaultValue;
                }
            }
            return result;
        }

        /// <summary>
        /// 转换成中文的星期
        /// </summary>
        /// <param name="dt">日期</param>
        /// <returns>返回星期</returns>
        public static string ConvertToZhWeek(DateTime dt)
        {
            string week = string.Empty;
            switch (dt.DayOfWeek.ToString())
            {
                case "Monday":
                    week = "星期一";
                    break;
                case "Tuesday":
                    week = "星期二";
                    break;
                case "Wednesday":
                    week = "星期三";
                    break;
                case "Thursday":
                    week = "星期四";
                    break;
                case "Friday":
                    week = "星期五";
                    break;
                case "Saturday":
                    week = "星期六";
                    break;
                case "Sunday":
                    week = "星期日";
                    break;
            }
            return week;
        }

        /// <summary>
        ///  根据数据日期类型 转化日期
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue"></param>
        /// <param name="dateFormat">输入日期格式 比如  yyyyMMdd</param>
        /// <returns></returns>
        public static DateTime ConvertToDateTime(object obj, DateTime defaultValue, string dateFormat)
        {
            DateTime result = defaultValue;

            if (obj != null)
            {
                //日期验证
                IFormatProvider ifp = new CultureInfo("zh-TW", true);

                DateTime.TryParseExact(obj.ToString(), dateFormat, ifp, DateTimeStyles.None, out result);
            }
            return result;
        }

        public static decimal ToDecimal(object obj)
        {
            decimal i = 0M;
            try
            {
                i = Convert.ToDecimal(obj);
                return i;
            }
            catch (Exception)
            {
                return 0.00M;
            }
        }
        /// <summary>
        /// 获取最终字符串(排除DBNull,null,string.Empty 或空值后的真实值) 
        /// 注:如果为DBNull,null,string.Empty 或空值,则返回string.Empty
        /// </summary>
        /// <param name="objString"></param>
        /// <returns></returns>
        public static string FinalString(object objString)
        {
            if (!ValidatHelper.IsDBNullOrNullOrEmptyString(objString))
                return objString.ToString();
            else
                return string.Empty;
        }

        /// <summary>
        /// 获取最终字符串(排除null,string.Empty 或空值后的真实值)
        /// 注:如果为DBNull,null,string.Empty 或空值,则返回string.Empty
        /// </summary>
        /// <param name="objString"></param>
        /// <returns></returns>
        public static string FinalString(string objString)
        {
            if (!ValidatHelper.IsNullOrEmptyString(objString))
                return objString;
            else
                return string.Empty;
        }

        /// <summary>
        /// 转换为int类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <param name="numStyle">数字格式</param>
        /// <returns></returns>
        public static int ConvertToInt(object obj, int defaultValue, NumberStyles numStyle)
        {
            int result = defaultValue;
            if (obj != null && obj != DBNull.Value)
            {
                if (!int.TryParse(obj.ToString().Trim(), numStyle, null, out result))
                {
                    result = defaultValue;
                }
            }
            return result;
        }

        /// <summary>
        /// 转换为int类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <param name="numStyle">数字格式</param>
        /// <returns></returns>
        public static byte ConvertToByte(object obj, byte defaultValue, NumberStyles numStyle)
        {
            Byte result = defaultValue;
            if (obj != null && obj != DBNull.Value)
            {
                if (!Byte.TryParse(obj.ToString().Trim(), numStyle, null, out result))
                {
                    result = defaultValue;
                }
            }
            return result;
        }

        /// <summary>
        /// 转换为int类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <returns></returns>
        public static int ConvertToInt(object obj, int defaultValue)
        {
            return ConvertToInt(obj, defaultValue, NumberStyles.Number);
        }

        /// <summary>
        /// 转换为int类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <returns></returns>
        public static byte ConvertToByte(object obj, Byte defaultValue)
        {
            return ConvertToByte(obj, defaultValue, NumberStyles.Number);
        }

        /// <summary>
        /// 转换为decimal类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <returns></returns>
        public static decimal ConvertToDecimal(object obj, decimal defaultValue)
        {
            decimal result = defaultValue;
            if (obj != null && obj != DBNull.Value)
            {
                if (!decimal.TryParse(obj.ToString().Trim(), out result))
                {
                    result = defaultValue;
                }
            }
            return result;
        }


        /// <summary>
        /// 转换为decimal类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultValue">返回的默认值</param>
        /// <returns></returns>
        public static double ConvertToDouble(object obj, double defaultValue)
        {
            double result = defaultValue;
            if (obj != null && obj != DBNull.Value)
            {
                if (!double.TryParse(obj.ToString().Trim(), out result))
                {
                    result = 0d;
                }
            }
            return result;
        }

        /// <summary>
        /// 将日期和时间的指定字符串表示形式转换为其等效的System.DateTime。
        /// </summary>
        /// <param name="strDateTime">日期和时间的指定字符串表示形式</param>
        /// <returns>日期时间</returns>
        public static DateTime? ParseDateTime(string strDateTime)
        {
            DateTime retDateTime;
            if (!String.IsNullOrEmpty(strDateTime))
                strDateTime = strDateTime.Trim();

            if (string.IsNullOrEmpty(strDateTime))
                return null;

            if (!DateTime.TryParse(strDateTime, out retDateTime))
            {
                CultureInfo zhCN = new CultureInfo("zh-CN");
                string[] formats = { "yyyyMMdd", "yyyyMMddHH", "yyyyMMddHHmm", "yyyyMMddHHmmss" };
                if (!DateTime.TryParseExact(strDateTime, formats, zhCN, DateTimeStyles.None, out retDateTime))
                {
                    return null;
                }
            }

            return retDateTime;
        }

        /// <summary>
        /// 转换日期格式为yyyy-MM-dd
        /// </summary>
        /// <param name="date">要转换的日期(yyyyMMdd)</param>
        /// <returns></returns>
        public static DateTime ConverDate(string date)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(date, @"^\d{8}$"))
            {
                StringBuilder stbDate = new StringBuilder();
                stbDate.Append(date.Substring(0, 4) + "-");
                stbDate.Append(date.Substring(4, 2) + "-");
                stbDate.Append(date.Substring(6, 2));
                if (ValidatHelper.IsStringDate(stbDate.ToString()))
                {
                    return Convert.ToDateTime(stbDate.ToString());
                }
                else
                {
                    throw new Exception("日期必须是数字");
                }
            }
            else
            {
                throw new Exception("日期必须是数字");
            }
        }
    }
View Code

EnumHelper

技术分享
public class EnumHelper
    {
        /// <summary>
        /// 转换如:"enum1,enum2,enum3"字符串到枚举值
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="obj">枚举字符串</param>
        /// <returns></returns>
        public static T Parse<T>(string obj)
        {
            if (string.IsNullOrEmpty(obj))
                return default(T);
            else
                return (T)Enum.Parse(typeof(T), obj);
        }

        public static T TryParse<T>(string obj, T defT = default(T))
        {
            try
            {
                return Parse<T>(obj);
            }
            catch
            {
                return defT;
            }
        }

        public static readonly string ENUM_TITLE_SEPARATOR = ",";
        /// <summary>
        /// 根据枚举值,返回描述字符串
        /// 如果多选枚举,返回以","分割的字符串
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetEnumTitle(Enum e, Enum language = null)
        {
            if (e == null)
            {
                return "";
            }
            string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries);
            Type type = e.GetType();
            string ret = "";
            foreach (string enumValue in valueArray)
            {
                System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim());
                if (fi == null)
                    continue;
                EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[];
                if (attrs != null && attrs.Length > 0 && attrs[0].IsDisplay)
                {
                    ret += attrs[0].Title + ENUM_TITLE_SEPARATOR;
                }
            }
            return ret.TrimEnd(ENUM_TITLE_SEPARATOR.ToArray());
        }

        /// <summary>
        /// 根据枚举值,返回描述字符串
        /// 如果多选枚举,返回以","分割的字符串
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetAllEnumTitle(Enum e, Enum language = null)
        {
            if (e == null)
            {
                return "";
            }
            string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries);
            Type type = e.GetType();
            string ret = "";
            foreach (string enumValue in valueArray)
            {
                System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim());
                if (fi == null)
                    continue;
                EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[];
                if (attrs != null && attrs.Length > 0)
                {
                    ret += attrs[0].Title + ENUM_TITLE_SEPARATOR;
                }
            }
            return ret.TrimEnd(ENUM_TITLE_SEPARATOR.ToArray());
        }

        public static EnumTitleAttribute GetEnumTitleAttribute(Enum e, Enum language = null)
        {
            if (e == null)
            {
                return null;
            }
            string[] valueArray = e.ToString().Split(ENUM_TITLE_SEPARATOR.ToArray(), StringSplitOptions.RemoveEmptyEntries);
            Type type = e.GetType();
            EnumTitleAttribute ret = null;
            foreach (string enumValue in valueArray)
            {
                System.Reflection.FieldInfo fi = type.GetField(enumValue.Trim());
                if (fi == null)
                    continue;
                EnumTitleAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[];
                if (attrs != null && attrs.Length > 0)
                {
                    ret = attrs[0];
                    break;
                }
            }
            return ret;
        }

        public static string GetDayOfWeekTitle(DayOfWeek day, Enum language = null)
        {
            switch (day)
            {
                case DayOfWeek.Monday:
                    return "周一";
                case DayOfWeek.Tuesday:
                    return "周二";
                case DayOfWeek.Wednesday:
                    return "周三";
                case DayOfWeek.Thursday:
                    return "周四";
                case DayOfWeek.Friday:
                    return "周五";
                case DayOfWeek.Saturday:
                    return "周六";
                case DayOfWeek.Sunday:
                    return "周日";
                default:
                    return "";
            }
        }

        /// <summary>
        /// 返回键值对,建为枚举的EnumTitle中指定的名称和近义词名称,值为枚举项
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="language"></param>
        /// <returns></returns>
        public static Dictionary<string, T> GetTitleAndSynonyms<T>(Enum language = null) where T : struct
        {
            Dictionary<string, T> ret = new Dictionary<string, T>();
            //枚举值
            Array arrEnumValue = http://www.mamicode.com/typeof(T).GetEnumValues();
            foreach (object enumValue in arrEnumValue)
            {
                System.Reflection.FieldInfo fi = typeof(T).GetField(enumValue.ToString());
                if (fi == null)
                {
                    continue;
                }

                EnumTitleAttribute[] arrEnumTitleAttr = fi.GetCustomAttributes(typeof(EnumTitleAttribute), false) as EnumTitleAttribute[];
                if (arrEnumTitleAttr == null || arrEnumTitleAttr.Length < 1 || !arrEnumTitleAttr[0].IsDisplay)
                {
                    continue;
                }

                if (!ret.ContainsKey(arrEnumTitleAttr[0].Title))
                {
                    ret.Add(arrEnumTitleAttr[0].Title, (T)enumValue);
                }

                if (arrEnumTitleAttr[0].Synonyms == null || arrEnumTitleAttr[0].Synonyms.Length < 1)
                {
                    continue;
                }

                foreach (string s in arrEnumTitleAttr[0].Synonyms)
                {
                    if (!ret.ContainsKey(s))
                    {
                        ret.Add(s, (T)enumValue);
                    }
                }
            }//using
            return ret;
        }

        /// <summary>
        /// 根据枚举获取包含所有所有值和描述的哈希表,其文本是由应用在枚举值上的EnumTitleAttribute设定
        /// </summary>
        /// <returns></returns>
        public static Dictionary<T, string> GetItemListByAttr<T>(Enum language = null) where T : struct
        {
            return GetItemValueListByAttr<T, T>(false, language);
        }
        public static Dictionary<T, string> GetItemList<T>(Enum language = null) where T : struct
        {
            return GetItemValueList<T, T>(false, language);
        }

        /// <summary>
        /// 根据枚举获取包含所有所有值和描述的哈希表,其文本是由应用在枚举值上的EnumTitleAttribute设定
        /// </summary>
        /// <returns></returns>
        public static Dictionary<T, string> GetAllItemList<T>(Enum language = null) where T : struct
        {
            return GetItemValueListByAttr<T, T>(true, language);
        }

        /// <summary>
        /// 获取枚举所有项的标题,其文本是由应用在枚举值上的EnumTitleAttribute设定
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="language">语言</param>
        /// <returns></returns>
        public static Dictionary<int, string> GetItemValueListByAttr<T>(Enum language = null) where T : struct
        {
            return GetItemValueListByAttr<T, int>(false, language);
        }

        /// <summary>
        /// 获取枚举所有项的标题,其文本是由应用在枚举值上的EnumTitleAttribute设定
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="isAll">是否生成“全部”项</param>
        /// <param name="language">语言</param>
        /// <returns></returns>
        public static Dictionary<TKey, string> GetItemValueListByAttr<T, TKey>(bool isAll, Enum language = null) where T : struct
        {
            if (!typeof(T).IsEnum)
            {
                throw new Exception("参数必须是枚举!");
            }
            Dictionary<TKey, string> ret = new Dictionary<TKey, string>();

            var titles = EnumHelper.GetItemAttributeList<T>().OrderBy(t => t.Value.Order);
            foreach (var t in titles)
            {
                if (!isAll && (!t.Value.IsDisplay || t.Key.ToString() == "None"))
                    continue;

                if (t.Key.ToString() == "None" && isAll)
                {
                    ret.Add((TKey)(object)t.Key, "全部");
                }
                else
                {
                    if (!string.IsNullOrEmpty(t.Value.Title))
                        ret.Add((TKey)(object)t.Key, t.Value.Title);
                }
            }

            return ret;
        }
        /// <summary>
        /// 获取枚举所有项的标题
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="isAll"></param>
        /// <param name="language"></param>
        /// <returns></returns>
        public static Dictionary<TKey, string> GetItemValueList<T, TKey>(bool isAll, Enum language = null) where T : struct
        {
            if (!typeof(T).IsEnum)
            {
                throw new Exception("参数必须是枚举!");
            }
            Dictionary<TKey, string> ret = new Dictionary<TKey, string>();

            var titles = typeof(T).GetEnumValues();
            foreach (var t in titles)
            {
                ret.Add((TKey)t, t.ToString());
            }
            return ret;
        }
        public static List<T> GetItemKeyList<T>(Enum language = null) where T : struct
        {
            List<T> list = new List<T>();
            Array array = typeof(T).GetEnumValues();
            foreach (object t in array)
            {
                list.Add((T)t);
            }
            return list;
        }

        public static Dictionary<T, EnumTitleAttribute> GetItemAttributeList<T>(Enum language = null) where T : struct
        {
            if (!typeof(T).IsEnum)
            {
                throw new Exception("参数必须是枚举!");
            }
            Dictionary<T, EnumTitleAttribute> ret = new Dictionary<T, EnumTitleAttribute>();

            Array array = typeof(T).GetEnumValues();
            foreach (object t in array)
            {
                EnumTitleAttribute att = GetEnumTitleAttribute(t as Enum, language);
                if (att != null)
                    ret.Add((T)t, att);
            }

            return ret;
        }

        /// <summary>
        /// 获取枚举所有项的标题,其文本是由应用在枚举值上的EnumTitleAttribute设定
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <param name="isAll">是否生成“全部”项</param>
        /// <param name="language">语言</param>
        /// <returns></returns>
        public static Dictionary<TKey, string> GetAllItemValueListByAttr<T, TKey>(Enum language = null) where T : struct
        {
            return GetItemValueListByAttr<T, TKey>(true, language);
        }


        /// <summary>
        /// 获取一个枚举的键值对形式
        /// </summary>
        /// <typeparam name="TEnum">枚举类型</typeparam>
        /// <param name="exceptTypes">排除的枚举</param>
        /// <returns></returns>
        public static Dictionary<int, string> GetEnumDictionaryByAttr<TEnum>(IEnumerable<TEnum> exceptTypes = null) where TEnum : struct
        {
            var dic = GetItemListByAttr<TEnum>();

            Dictionary<int, string> dicNew = new Dictionary<int, string>();
            foreach (var d in dic)
            {
                if (exceptTypes != null && exceptTypes.Contains(d.Key))
                {
                    continue;
                }
                dicNew.Add(d.Key.GetHashCode(), d.Value);
            }
            return dicNew;
        }


        public static Dictionary<int, string> GetEnumDictionary<TEnum>(IEnumerable<TEnum> exceptTypes = null) where TEnum : struct
        {
            var dic = GetItemList<TEnum>();

            Dictionary<int, string> dicNew = new Dictionary<int, string>();
            foreach (var d in dic)
            {
                if (exceptTypes != null && exceptTypes.Contains(d.Key))
                {
                    continue;
                }
                dicNew.Add(d.Key.GetHashCode(), d.Value);
            }
            return dicNew;
        }
    }

    public class EnumTitleAttribute : Attribute
    {
        private bool _IsDisplay = true;

        public EnumTitleAttribute(string title, params string[] synonyms)
        {
            Title = title;
            Synonyms = synonyms;
            Order = int.MaxValue;
        }
        public bool IsDisplay { get { return _IsDisplay; } set { _IsDisplay = value; } }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Letter { get; set; }
        /// <summary>
        /// 近义词
        /// </summary>
        public string[] Synonyms { get; set; }
        public int Category { get; set; }
        public int Order { get; set; }
    }
View Code

HttpHelper

技术分享
public class HttpHelper
    {
        /// <summary>
        /// POST方法获取某URL的页面内容
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="parms">参数</param>
        /// <param name="encoding">编码</param>
        /// <returns>页面内容</returns>
        public static string PostResponse(string url, string parms, string encoding, string ContentType = "text/xml")
        {
            var result = string.Empty;
            try
            {

                var mRequest = (HttpWebRequest)WebRequest.Create(url);
                //相应请求的参数
                var data =http://www.mamicode.com/ Encoding.GetEncoding(encoding).GetBytes(parms);
                mRequest.Method = "Post";
                mRequest.ContentType = ContentType;
                mRequest.ContentLength = data.Length;
                mRequest.Timeout = 60000;
                mRequest.KeepAlive = true;
                mRequest.ProtocolVersion = HttpVersion.Version10;
                //请求流
                var requestStream = mRequest.GetRequestStream();
                requestStream.Write(data, 0, data.Length);
                requestStream.Close();
                //响应流
                var mResponse = mRequest.GetResponse() as HttpWebResponse;
                var responseStream = mResponse.GetResponseStream();
                if (responseStream != null)
                {
                    var streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding));
                    //获取返回的信息
                    result = streamReader.ReadToEnd();
                    streamReader.Close();
                    responseStream.Close();
                }
            }
            catch
            {
                result = "获取数据失败,请重试!";
            }
            return result;
        }

        /// <summary>
        /// Get方法获取某URL的页面内容
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="encoding">编码</param>
        /// <returns>页面内容</returns>
        public static string GetResponse(string url, System.Text.Encoding encoding, int timeOut = 60000)
        {
            try
            {
                System.Net.HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
                req.Method = "GET";
                req.ServicePoint.Expect100Continue = false;
                req.ServicePoint.UseNagleAlgorithm = false;
                req.Timeout = timeOut;
                string response = string.Empty;
                using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
                {
                    //Output(string.Format("{0},StatusCode:{1},{2}", url, res.StatusCode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff")));
                    using (System.IO.StreamReader reader = new System.IO.StreamReader(
                                                           res.GetResponseStream()
                                                         , encoding))
                    {
                        response = reader.ReadToEnd();
                    }
                    return response;
                    //Output(response);
                }
            }
            catch { return string.Empty; }
        }

        /// <summary>
        /// Get方法获取某URL的页面内容
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="encoding">编码</param>
        /// <returns>页面内容</returns>
        public static string GetResponse(string url, string encoding, int timeOut)
        {
            string result = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = timeOut;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream resStream = response.GetResponseStream();
                Encoding encode = Encoding.GetEncoding(encoding);
                if (resStream != null)
                {
                    StreamReader readStream = new StreamReader(resStream, encode);
                    Char[] read = new Char[256];
                    int count = readStream.Read(read, 0, 256);
                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        result = result + str;
                        count = readStream.Read(read, 0, 256);
                    }
                    resStream.Close();
                }
            }
            catch
            {
                return string.Empty;
            }
            return result;
        }

        /// <summary>
        /// 通过POST提交方式获取XML数据
        /// </summary>
        /// <param name="requestXml">请求XML内容</param>
        /// <param name="url">请求URL</param>
        /// <param name="inputCharset">请求字符集</param>
        /// <returns></returns>
        public static XmlDocument GetXmlByPost(string requestXml, string url, string inputCharset)
        {
            if (string.IsNullOrEmpty(requestXml) || string.IsNullOrEmpty(url))
                return null;

            if (string.IsNullOrEmpty(inputCharset))
                inputCharset = "UTF-8";

            try
            {
                string rtnStr = string.Empty;
                byte[] data =http://www.mamicode.com/ Encoding.GetEncoding(inputCharset).GetBytes(requestXml);

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "Post";
                myRequest.ContentType = "text/xml";
                myRequest.ContentLength = data.Length;
                // 30秒超时时间
                myRequest.Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds;

                Stream newStream = myRequest.GetRequestStream();
                // Send the data
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                // Get response 
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding(inputCharset)))
                {
                    rtnStr = reader.ReadToEnd();
                    reader.Close();
                }
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(rtnStr);
                return xml;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// xml 转化成 dataset
        /// </summary>
        /// <param name="xmlData">xml数据</param>
        /// <returns></returns>
        public static DataSet ConvertXMLToDataSet(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }
        /// <summary>
        /// xml 转化成 datatable
        /// </summary>
        /// <param name="xmlData">xml数据</param>
        /// <returns></returns>
        public static DataTable ConvertXMLToDatatalbe(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataTable dt = new DataTable();
                stream = new StringReader(xmlData);
                reader = new XmlTextReader(stream);
                dt.ReadXml(reader);
                return dt;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }
    }
View Code

EnumUtil

技术分享
public static class EnumUtil
    {
        /// <summary>
        /// 获取枚举的数据源
        /// </summary>
        /// <returns>数据源</returns>
        public static List<EnumDataModel> GetEnumDataList<T>()
        {
            return EnumUtilData<T>.enumDataList;
        }

        /// <summary>
        /// 通过枚举获取描述信息
        /// </summary>
        /// <param name="enumValue">枚举字段</param>
        /// <returns>描述信息</returns>
        public static string GetDescriptionByValue<T>(int value)
        {
            return GetDescriptionByName<T>(value.ToString());
        }

        /// <summary>
        /// 通过枚举获取描述信息
        /// </summary>
        /// <param name="enumValue">枚举字段</param>
        /// <returns>描述信息</returns>
        public static string GetDescriptionByName<T>(string name)
        {
            T t = GetEnumByName<T>(name);

            return GetDescriptionByEnum<T>(t);
        }

        /// <summary>
        /// 通过枚举获取描述信息
        /// </summary>
        /// <param name="enumInstance">枚举</param>
        /// <returns>描述信息</returns>
        public static string GetDescriptionByEnum<T>(T enumInstance)
        {
            List<EnumDataModel> enumDataList = GetEnumDataList<T>();
            EnumDataModel enumData = enumDataList.Find(m => m.Value =http://www.mamicode.com/= enumInstance.GetHashCode());
            if (enumData != null)
            {
                return enumData.Description.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 通过枚举值得到枚举
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns>枚举</returns>
        public static T GetEnumByValue<T>(int value)
        {
            return GetEnumByName<T>(value.ToString());
        }

        /// <summary>
        /// 通过枚举值得到枚举
        /// </summary>
        /// <param name="name">枚举值</param>
        /// <returns>枚举</returns>
        public static T GetEnumByName<T>(string name)
        {
            string msg = string.Empty;
            try
            {
                Type t = typeof(T);
                return (T)System.Enum.Parse(t, name);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return default(T);
            }
        }

        /// <summary>
        /// 尝试转换枚举,失败则返回false
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="parsed"></param>
        /// <returns></returns>
        public static bool TryToEnum<T>(object value, out T parsed) where T : struct
        {
            bool isParsed = false;
            if (System.Enum.IsDefined(typeof(T), value))
            {
                parsed = (T)System.Enum.Parse(typeof(T), value.ToString());
                isParsed = true;
            }
            else
            {
                parsed = (T)System.Enum.Parse(typeof(T), System.Enum.GetNames(typeof(T))[0]);
            }
            return isParsed;
        }

        /// <summary>
        /// 根据枚举获取下拉框
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="defaultValue"></param>
        /// <param name="addChoose"></param>
        /// <returns></returns>
        public static List<SelectListItem> SelectListEnum<T>(int? defaultValue = http://www.mamicode.com/null, bool addChoose = true) where T : struct
        {
            var enumSelectListItem = new List<SelectListItem>();
            if (addChoose)
            {
                var listItem = new SelectListItem { Text = "请选择", Value = http://www.mamicode.com/"-1" };
                enumSelectListItem.Add(listItem);
            }
            var enumDataList = EnumUtil.GetEnumDataList<T>();

            enumSelectListItem.AddRange(from item in enumDataList
                                        let bl = defaultValue != null && item.Value =http://www.mamicode.com/= defaultValue
                                        select new SelectListItem { Text = item.Description, Value = http://www.mamicode.com/item.Value.ToString(), Selected = bl });
            return enumSelectListItem;

        }

        /// <summary>
        /// 内部实现类,缓存
        /// </summary>
        /// <typeparam name="Tenum">枚举类型</typeparam>
        private static class EnumUtilData<Tenum>
        {
            /// <summary>
            /// 缓存数据
            /// </summary>
            internal static readonly List<EnumDataModel> enumDataList;

            static EnumUtilData()
            {
                enumDataList = InitData();
            }

            /// <summary>
            /// 初始化数据,生成枚举和描述的数据表
            /// </summary>
            private static List<EnumDataModel> InitData()
            {
                List<EnumDataModel> enumDataList = new List<EnumDataModel>();

                EnumDataModel enumData = new EnumDataModel();
                Type t = typeof(Tenum);
                FieldInfo[] fieldInfoList = t.GetFields();
                foreach (FieldInfo tField in fieldInfoList)
                {
                    if (!tField.IsSpecialName)
                    {
                        enumData = new EnumDataModel();
                        enumData.Name = tField.Name;
                        enumData.Value = ((Tenum)System.Enum.Parse(t, enumData.Name)).GetHashCode();

                        DescriptionAttribute[] enumAttributelist = (DescriptionAttribute[])tField.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (enumAttributelist != null && enumAttributelist.Length > 0)
                        {
                            enumData.Description = enumAttributelist[0].Description;
                        }
                        else
                        {
                            enumData.Description = tField.Name;
                        }
                        enumDataList.Add(enumData);
                    }
                }
                return enumDataList;
            }
        }

        /// <summary>
        /// 枚举数据实体
        /// </summary>
        public class EnumDataModel
        {
            /// <summary>
            /// get or set 枚举名称
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// get or set 枚举值
            /// </summary>
            public int Value { get; set; }

            /// <summary>
            /// get or set 枚举描述
            /// </summary>
            public string Description { get; set; }
        }
    }
View Code

ValidatHelper

技术分享
public class ValidatHelper
    {
        /// <summary>
        /// 检测字符串的内容是否数字字符
        /// </summary>
        /// <param name="strTemp"></param>
        /// <returns></returns>
        public static bool IsNumeric(String strTemp)
        {
            if (String.IsNullOrEmpty(strTemp))
                return false;

            strTemp = strTemp.Replace(",", String.Empty);
            Regex regNum = new Regex(@"^[-]?\d+[.]?\d*$");
            return regNum.IsMatch(strTemp);
        }

        /// <summary>
        /// 判断一个字符串是否为邮件
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsEmail(string email)
        {
            Regex regex = new Regex(@"^\w+([-+.]\w+)*@(\w+([-.]\w+)*\.)+([a-zA-Z]+)+$", RegexOptions.IgnoreCase);
            return regex.Match(email).Success;
        }

        /// <summary>
        /// 判断一个字符串是否为Deceimal 类型
        /// </summary>
        /// <param name="_value">要判断的原数据</param>
        /// <returns>是否为Decimal类型</returns>
        public static bool IsDecimal(string _value)
        {
            decimal tmp;
            if (decimal.TryParse(_value, out tmp))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 是否是中文字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsCNChar(String str)
        {
            string strRegTxt = @"^[\u4e00-\u9fa5]{0,}$";
            if (!Regex.IsMatch(str, strRegTxt))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 检查一个字符串是否可以转化为日期,一般用于验证用户输入日期的合法性。
        /// </summary>
        /// <param name="_value">需验证的字符串。</param>
        /// <returns>是否可以转化为日期的bool值。</returns>
        public static bool IsStringDate(string _value)
        {
            DateTime dTime;
            try
            {
                dTime = DateTime.Parse(_value);
            }
            catch (FormatException)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 判断一个字符串是否为8位无符号整数
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsByte(string _value)
        {
            byte tmp;
            if (Byte.TryParse(_value, out tmp))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 判断一个字符串是否为短整型整数
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsInt16(string _value)
        {
            short tmp;
            if (Int16.TryParse(_value, out tmp))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 判断一个字符串是否为整数
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsInt32(string _value)
        {
            int tmp;
            if (Int32.TryParse(_value, out tmp))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 判断一个字符串是否为长整数
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsInt64(string _value)
        {
            long tmp;
            if (Int64.TryParse(_value, out tmp))
                return true;
            else
                return false;
        }


        /// <summary>
        /// 判断一个字符是否是bool类型
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsBoolean(string _value)
        {
            bool temp;
            if (bool.TryParse(_value, out temp))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 判断一个字符串是否为手机号码
        /// </summary>
        /// <param name="mobileNum"></param>
        /// <returns></returns>
        public static bool IsMobileNum(string mobileNum)
        {
            Regex regex = new Regex(@"^(13|14|15|18|17)[0-9]{9}$", RegexOptions.IgnoreCase);
            return regex.Match(mobileNum).Success;
        }

        /// <summary>
        /// 判断一个字符串是否为电话号码
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsPhoneNum(string _value)
        {
            Regex regex = new Regex(@"^(86)?(-)?(0\d{2,3})?(-)?(\d{7,8})(-)?(\d{3,5})?$", RegexOptions.IgnoreCase);
            return regex.Match(_value).Success;
        }

        /// <summary>
        /// 判断一个字符串是否为网址
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsUrl(string _value)
        {
            Regex regex = new Regex(@"(http://)?([\w-]+\.)*[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase);
            return regex.Match(_value).Success;
        }

        /// <summary>
        /// 是否是英文
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsEnChar(string _value)
        {
            Regex regex = new Regex(@"[a-zA-Z]{1,}");
            return regex.Match(_value).Success;
        }

        /// <summary>
        /// 判断一个字符串是否为IP地址
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsIP(string _value)
        {
            Regex regex = new Regex(@"^(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1})).(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1})).(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1})).(((2[0-4]{1}[0-9]{1})|(25[0-5]{1}))|(1[0-9]{2})|([1-9]{1}[0-9]{1})|([0-9]{1}))$", RegexOptions.IgnoreCase);
            return regex.Match(_value).Success;
        }

        /// <summary>
        /// 判断一个字符串是否为字母加数字
        /// Regex("[a-zA-Z0-9]?"
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static bool IsWordAndNum(string _value)
        {
            Regex regex = new Regex("[a-zA-Z0-9]?");
            return regex.Match(_value).Success;
        }

        /// <summary>
        /// 验证是否为金钱类型
        /// </summary>
        /// <param name="strMoney"></param>
        /// <returns></returns>
        public static bool IsMoney(string strMoney)
        {
            double money = 0;
            try
            {
                money = Convert.ToSingle(strMoney);
            }
            catch (FormatException)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 验证邮政编码
        /// </summary>
        /// <param name="strPostNo"></param>
        /// <returns></returns>
        public static bool IsPostNo(string strPostNo)
        {
            if (strPostNo.Trim().Length != 6)
                return false;
            Regex regex = new Regex(@"[1-9]\d{5}(?!\d)");
            return regex.Match(strPostNo).Success;
        }

        /// <summary>
        /// yyyyMMdd是否为合法的日期
        /// </summary>
        /// <param name="date">要检验的日期</param>
        /// <returns></returns>
        public static bool IsDate(string date)
        {
            DateTime dt;
            if (string.IsNullOrEmpty(date))
                return false;
            System.Globalization.CultureInfo zhCN = new System.Globalization.CultureInfo("zh-CN");
            string[] formats = { "yyyyMMdd", "yyyyMMddHH", "yyyyMMddHHmm", "yyyyMMddHHmmss" };
            return DateTime.TryParseExact(date, formats, zhCN, System.Globalization.DateTimeStyles.None, out dt);
        }

        /// <summary>
        /// 判断是否为字母
        /// </summary>
        /// <param name="value">要校验的字符串</param>
        /// <returns></returns>
        public static bool IsLetters(string value)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"^[a-zA-Z]");
        }

        /// <summary>
        /// 是否是日期类型
        /// </summary>
        /// <returns></returns>
        public static bool IsDateTime(string strDateValue)
        {
            string strRealValue = http://www.mamicode.com/null;
            if (IsNullOrEmptyString(strDateValue, out strRealValue))
                return false;
            DateTime dtDate = DateTime.MinValue;
            return DateTime.TryParse(strRealValue, out dtDate);
        }

        /// <summary>
        /// DataRow的value或从数据库中取出的Object型数据验证,验证取出的object是否是DBNull,空或null]
        /// 如果是DBNull,null或空字符串则返回true
        /// </summary>
        /// <param name="objSource">待验证的object</param>
        /// <returns>
        /// 如果是DBNull,null或空字符串则返回true
        /// </returns>
        public static bool IsDBNullOrNullOrEmptyString(object objSource)
        {
            if ((objSource == DBNull.Value) || (objSource == null))
                return true;
            string strSource = objSource.ToString();
            if (strSource.Trim() == string.Empty)
                return true;
            return false;
        }

        /// <summary>
        /// 验证是否是空或null字符串
        /// 如果是空或null则返回true,否则返回false
        /// </summary>
        /// <param name="strSource">待查看的string</param>
        /// <returns>
        /// 如果是空或null则返回true,否则返回false
        /// </returns>
        public static bool IsNullOrEmptyString(string strSource)
        {
            if (strSource == null)
                return true;
            if (strSource.Trim() == string.Empty)
                return true;
            return false;
        }

        /// <summary>
        /// 验证是否是空或null字符串
        /// 如果是空或null则返回true,strRealString为null或string.Empty
        /// 否则返回false,strRealString为经过Trim操作的String;
        /// </summary>
        /// <param name="strSource">待查看的string</param>
        /// <param name="strRealString">经过Trim操作的string</param>
        /// <returns>
        /// 如果是空或null则返回true,strRealString为null或string.Empty
        /// 否则返回false,strRealString为经过Trim操作的String;
        /// </returns>
        public static bool IsNullOrEmptyString(string strSource, out string strRealString)
        {
            strRealString = null;
            if (strSource == null)
                return true;
            strRealString = strSource.Trim();
            if (strRealString == string.Empty)
                return true;
            return false;
        }


        #region ip转换成long
        /// <summary>
        /// ip转换成long
        /// </summary>
        /// <param name="ipAdd"></param>
        /// <returns></returns>
        public static long GetIpNum(string ipAdd)
        {
            string[] ipArr = ipAdd.Split(.);
            if (ipArr.Length == 4)
            {
                long a = int.Parse(ipArr[0]);
                long b = int.Parse(ipArr[1]);
                long c = int.Parse(ipArr[2]);
                long d = int.Parse(ipArr[3]);
                return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
            }
            else
            {
                return -1;
            }
        }
        #endregion

        /// <summary>
        /// 判断IP是否在范围之内
        /// </summary>
        /// <param name="ipAdd"></param>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public static bool IsInIP(long ipAdd, long begin, long end)
        {
            return ipAdd >= begin && ipAdd <= end;
        }

        #region 判断是否是IP地址格式 0.0.0.0
        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

        #endregion

        #region 判断是否有特殊字符
        /// <summary>
        ///判断是否有特殊字符
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool IsInvalidString(string text)
        {
            bool isInvalidstring = false;
            if (string.IsNullOrWhiteSpace(text))
                return false;
            if (Regex.IsMatch(text, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\‘]"))
                isInvalidstring = true;

            if (Regex.IsMatch(text, @"<script[^>]*?>.*?</script>")
                || Regex.IsMatch(text, @"<style[\s\S]+</style *>")
                || Regex.IsMatch(text, @"<(.[^>]*)>")
                || Regex.IsMatch(text, @"([\r\n])[\s]+")
                || Regex.IsMatch(text, @"-->")
                || Regex.IsMatch(text, @"<!--.*")
                || Regex.IsMatch(text, @"&(quot|#34);")
                || Regex.IsMatch(text, @"&(amp|#38);")
                || Regex.IsMatch(text, @"&(lt|#60);")
                || Regex.IsMatch(text, @"&(gt|#62);")
                || Regex.IsMatch(text, @"&(nbsp|#160);")
                || Regex.IsMatch(text, @"&(iexcl|#161);")
                || Regex.IsMatch(text, @"&(cent|#162);")
                || Regex.IsMatch(text, @"&(pound|#163);")
                || Regex.IsMatch(text, @"&(copy|#169);")
                || Regex.IsMatch(text, @"<")
                || Regex.IsMatch(text, @">")
                || Regex.IsMatch(text, @"\r\n")
                )
            {
                isInvalidstring = true;
            }

            return isInvalidstring;
        }
        #endregion


        #region 判断是否含有SQL字符

        private static string[] _nvalidSqlString = new string[] { Regex.Escape("/*"), Regex.Escape(@"*/"), "--", "", "declare", "select", "into", "insert", "update", "delete", "drop", "create", "exec", "master" };

        public static bool IsInvalidSqlString(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                goto end;
            }
            if (Regex.IsMatch(text, string.Join("|", _nvalidSqlString)))
            {
                return true;
            }
        end: return false;
        }

        #endregion

        #region 用户手机号码加密
        public static string EncryptMobile(string Mobile)
        {

            Regex regex = new Regex(@"(?<=13\d|15\d|18\d|147)\d{4}(?=\d{4})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (regex.IsMatch(Mobile))
            {
                return regex.Replace(Mobile, "****");
            }
            else
            {
                return Mobile;
            }
        }

        #endregion

        #region 用户证件号加密
        public static string EncryptCardNo(string CardNo)
        {
            Regex regex = new Regex(@"(?<!^).(?!$)");
            return regex.Replace(CardNo, "*");
        }
        #endregion

        #region 验证乘客姓名是否为繁体字
        /// <summary>
        /// 验证乘客姓名是否为繁体字
        /// </summary>
        /// <param name="name">乘客姓名</param>
        /// <returns>非GB2312的字符</returns>
        public static string GB2312_Check(string name)
        {
            string temp = Regex.Replace(name, "[A-Za-z]|/| ", "");
            if (temp.Length == 0)
                return string.Empty;
            string strError = string.Empty;
            byte[] bttemp = System.Text.Encoding.Default.GetBytes(temp);
            for (int i = 0; i < bttemp.Length; i = i + 2)
            {
                if (bttemp[i] >= 176 && bttemp[i] <= 247 &&
                    bttemp[i + 1] >= 160 && bttemp[i + 1] <= 254)
                {
                    continue;
                }
                else
                {
                    strError += temp[i / 2];
                }
            }
            return strError;
        }
        #endregion

        #region 是否省份
        /// <summary>
        /// timmy  20130516
        /// </summary>
        /// <param name="province"></param>
        /// <returns></returns>
        public static bool IsProvince(string province)
        {
            string[] provinceList = { "安徽", "北京", "福建", "甘肃", "广东", "广西", "贵州", "海南", "河北", "河南", "黑龙江", "湖北", "湖南", "吉林", "江苏", "江西", "辽宁", "内蒙古", "宁夏", "青海", "山东", "山西", "陕西", "上海", "四川", "天津", "西藏", "新疆", "云南", "浙江", "重庆", "香港", "澳门", "台湾" };
            if (!string.IsNullOrEmpty(province) && provinceList.Contains(province))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 数字验证
        /// <summary>
        /// 是否是数字
        /// </summary>
        /// <param name="strNum">待测试的字符串</param>
        /// <returns>是则返回true,否则返回false</returns>
        public static bool IsNumber(string strNum)
        {
            if (strNum == null)
                return false;
            return Regex.IsMatch(strNum.Trim(), "^(0|[1-9][0-9]*)$");
        }

        #endregion
    }
View Code

 

.net工具类