.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("日期必须是数字");
            }
        }
    }

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 = 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; }
    }

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 = 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 = 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();
            }
        }
    }

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 == 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 = null, bool addChoose = true) where T : struct
        {
            var enumSelectListItem = new List<SelectListItem>();
            if (addChoose)
            {
                var listItem = new SelectListItem { Text = "请选择", Value = "-1" };
                enumSelectListItem.Add(listItem);
            }
            var enumDataList = EnumUtil.GetEnumDataList<T>();

            enumSelectListItem.AddRange(from item in enumDataList
                                        let bl = defaultValue != null && item.Value == defaultValue
                                        select new SelectListItem { Text = item.Description, Value = 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; }
        }
    }

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 = 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
    }

时间: 2024-10-08 23:51:46

.net工具类的相关文章

Arrays工具类

Arraysd的静态方法能够方便的对数组进行操作,每个方法也加了注释 : 程序: import java.util.*;public class Array{        public static void main(String[] args){                int[]  arr={1,3,4,2};                System.out.println("排序前:");                printArray(arr);//打印原数组

常用工具类(System,Runtime,Date,Calendar,Math)

一.Sy 一个java.lang包中的静态工具类. 三大字段: static PrintStream err "标准"错误输出流. static InputStream in "标准"输入流. static PrintStream out "标准"输出流. 其他常用方法: 描述系统信息: 获取系统属性信息: static Properties getProperties(): (Properties是Hashtable的子类,也就是Map 的子类

iOS 中的正则匹配(工具类)

正则表达式 正则表达式是对字符串操作的一种逻辑公式, 用事先定义好的一些特定字符.及这些特定字符的组合, 组成一个"规则字符串", 这个"规则字符串"用来表达对字符串的一种过滤逻辑, 正则表达式就是用于描述这些规则的工具, 或者说, 正则表达式就是记录文本规则的代码. 在开发中, 我们经常会有查找符合某些复杂规则的字符串的需要, 比如数据校验: 判断用户的输入是否合法(如:用户注册的时候,QQ号码,电话号码,邮箱是否符合要求) 下面让我们先来看看正则匹配常用的一些字

(九十五)音效播放方法和工具类的制作

音效通过AVFoundation框架实现,是通过函数而不是方法,因此需要进行桥接等操作,具体步骤如下. 进行音效播放,首先要得到音效的URL(只能是本地音频),然后转换为音效ID(唯一),通过ID播放音效. [音效播放方法] ①导入框架主头文件 #import <AVFoundation/AVFoundation.h> ②通过Bundle拿到本地音效,然后调用AudioServicesCreateSystemSoundID函数得到音效ID,ID为0代表无效,以此为依据可进行懒加载 @inter

spring endpoint工具类

工具类代码 @Controller public class EndpointDocController {     private final RequestMappingHandlerMapping handlerMapping;     @Autowired     public EndpointDocController(RequestMappingHandlerMapping handlerMapping) {         this.handlerMapping = handler

web常用的工具类总结

数据库的链接的操作类 package utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class DBConnection { private static final String DBDRIVER = "com.m

字符串工具类(指定字符串的长度和判断是否为空等方法)

package com.sec.util; /** * 字符串工具类 * @author Administrator * */public class StringUtil { /** * 过滤<,>,\n 字符串的方法 * @param input * @return */ public static String filterHTML(String input){ if(input == null || input.length() == 0){ return input; } input

java并发的艺术-读书笔记-第八章常用的并发工具类

jdk中提供了几个非常有用的工具类,分别是CountDownLatch,CyclicBarrier和semaphore exchanger CountDownLatch:允许一个或者多个线程等待其他线程完成操作 public class CountDownLatchTest{ static CountDownLatch c = new CountDownLatch(2); public static void main(String[] args){ new Thread(new Runnabl

java分页的实现(后台工具类和前台jsp页面)

1.首先,新建一个类Page.java 1 public class Page implements Serializable { 2 private static final long serialVersionUID = -3198048449643774660L; 3 private int pageNow = 1; // 当前页数 4 private int pageSize = 10; // 每页显示记录的条数 5 private int totalCount; // 总记录条数 6

【Android 工具类】经常使用工具类(方法)大全

收集经常使用的工具类或者方法: 1.获取手机分辨率 /** * 获取手机分辨率 */ public static String getDisplayMetrix(Context context) { if (Constant.Screen.SCREEN_WIDTH == 0 || Constant.Screen.SCREEN_HEIGHT == 0) { if (context != null) { int width = 0; int height = 0; SharedPreferences