www.pudn.com > MyShop.rar > Utils.cs


using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Security.Cryptography; 
using System.Text.RegularExpressions; 
using System.Web; 
using System.Web.UI; 
using Microsoft.VisualBasic; 
using System.IO; 
using System.Security.Permissions; 
using System.Collections; 
using System.Runtime.InteropServices; 
 
namespace MyShop.BLL 
{ 
    ///  
    /// 工具类 
    ///  
    public class Utils 
    { 
        #region String字符串类 
        ///  
		/// 返回字符串真实长度, 1个汉字长度为2 
		///  
		///  
        public static int GetStringLength(string str) 
        { 
            return Encoding.Default.GetBytes(str).Length; 
        } 
        ///  
        /// 过滤非法字符 
        ///  
        ///  
        ///  
        public static string ReplaceBadChar(string str) 
        { 
            if (string.IsNullOrEmpty(str)) 
                return ""; 
            string strBadChar, tempChar; 
            string[] arrBadChar; 
            strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\","; 
            arrBadChar = SplitString(strBadChar, ","); 
            tempChar = str; 
            for (int i = 0; i < arrBadChar.Length; i++) 
            { 
                if (arrBadChar[i].Length > 0) 
                    tempChar = tempChar.Replace(arrBadChar[i], ""); 
            } 
            return tempChar; 
        } 
 
 
        ///  
        /// 检查是否含有非法字符 
        ///  
        /// 要检查的字符串 
        ///  
        public static bool ChkBadChar(string str) 
        { 
            bool result = false; 
            if (string.IsNullOrEmpty(str)) 
                return result; 
            string strBadChar, tempChar; 
            string[] arrBadChar; 
            strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\""; 
            arrBadChar = SplitString(strBadChar, ","); 
            tempChar = str; 
            for (int i = 0; i < arrBadChar.Length; i++) 
            { 
                if (tempChar.IndexOf(arrBadChar[i]) >= 0) 
                    result = true; 
            } 
            return result; 
        } 
 
 
        ///  
        /// 分割字符串 
        ///  
        public static string[] SplitString(string strContent, string strSplit) 
        { 
            int i = strContent.IndexOf(strSplit); 
            if (strContent.IndexOf(strSplit) < 0) 
            { 
                string[] tmp = { strContent }; 
                return tmp; 
            } 
            //return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase); 
 
            return Regex.Split(strContent, @strSplit.Replace(".", @"\.")); 
        } 
        ///  
        /// 检测是否有危险的可能用于链接的字符串 
        ///  
        /// 要判断字符串 
        /// 判断结果 
        public static bool IsSafeUserInfoString(string str) 
        { 
            return !Regex.IsMatch(str, @"/^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|$guestexp/is"); 
        } 
 
        ///  
        /// string型转换为int型 
        ///  
        /// 要转换的字符串 
        /// 转换后的int类型结果.如果要转换的字符串是非数字,则返回-1. 
        public static int StrToInt(object strValue) 
        { 
            int defValue = -1; 
            if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10)) 
            { 
                return defValue; 
            } 
 
            string val = strValue.ToString(); 
            string firstletter = val[0].ToString(); 
 
            if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1) 
            { 
                return defValue; 
            } 
            else if (val.Length == 10 && !IsNumber(firstletter)) 
            { 
                return defValue; 
            } 
 
 
            int intValue = defValue; 
            if (strValue != null) 
            { 
                bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString()); 
                if (IsInt) 
                { 
                    intValue = Convert.ToInt32(strValue); 
                } 
            } 
 
            return intValue; 
        } 
 
        ///  
        /// string型转换为int型 
        ///  
        /// 要转换的字符串 
        /// 缺省值 
        /// 转换后的int类型结果 
        public static int StrToInt(object strValue, int defValue) 
        { 
            if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10)) 
            { 
                return defValue; 
            } 
 
            string val = strValue.ToString(); 
            string firstletter = val[0].ToString(); 
 
            if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1) 
            { 
                return defValue; 
            } 
            else if (val.Length == 10 && !IsNumber(firstletter)) 
            { 
                return defValue; 
            } 
 
 
            int intValue = defValue; 
            if (strValue != null) 
            { 
                bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString()); 
                if (IsInt) 
                { 
                    intValue = Convert.ToInt32(strValue); 
                } 
            } 
 
            return intValue; 
        } 
 
        ///  
        /// string型转换为float型 
        ///  
        /// 要转换的字符串 
        /// 缺省值 
        /// 转换后的int类型结果 
        public static float StrToFloat(object strValue, float defValue) 
        { 
            if ((strValue == null) || (strValue.ToString().Length > 10)) 
            { 
                return defValue; 
            } 
 
            float intValue = defValue; 
            if (strValue != null) 
            { 
                bool IsFloat = new Regex(@"^([-]|[0-9])[0-9]*(\.\w*)?$").IsMatch(strValue.ToString()); 
                if (IsFloat) 
                { 
                    intValue = Convert.ToSingle(strValue); 
                } 
            } 
            return intValue; 
        } 
 
 
        ///  
        /// string型转换为时间型 
        ///  
        /// 要转换的字符串 
        /// 缺省值 
        /// 转换后的时间类型结果 
        public static DateTime StrToDateTime(object strValue,DateTime defValue) 
        { 
            if ((strValue == null) || (strValue.ToString().Length > 20)) 
            { 
                return defValue; 
            } 
 
            DateTime intValue ; 
 
            if (!DateTime.TryParse(strValue.ToString(), out intValue)) 
            { 
                intValue =  defValue; 
            } 
            return intValue; 
        } 
 
 
        ///  
        /// 判断给定的字符串(strNumber)是否是数值型 
        ///  
        /// 要确认的字符串 
        /// 是则返加true 不是则返回 false 
        public static bool IsNumber(string strNumber) 
        { 
            return new Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber); 
        } 
 
 
        ///  
        /// 检测是否符合email格式 
        ///  
        /// 要判断的email字符串 
        /// 判断结果 
        public static bool IsValidEmail(string strEmail) 
        { 
            return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 
        } 
 
 
        ///  
        /// 检测是否符合url格式,前面必需含有http:// 
        ///  
        ///  
        ///  
        public static bool IsURL(string url) 
        { 
            return Regex.IsMatch(url,@"^http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$"); 
        } 
 
        ///  
        /// 检测是否符合电话格式 
        ///  
        ///  
        ///  
        public static bool IsPhoneNumber(string phoneNumber) 
        { 
            return Regex.IsMatch(phoneNumber,@"^(\(\d{3}\)|\d{3}-)?\d{7,8}$"); 
        } 
 
 
 
        ///  
        /// 检测是否符合时间格式 
        ///  
        ///  
        public static bool IsTime(string timeval) 
        { 
            return Regex.IsMatch(timeval, @"20\d{2}\-[0-1]{1,2}\-[0-3]?[0-9]?(\s*((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?))?"); 
        } 
 
 
 
        ///  
        /// 检测是否符合身份证号码格式 
        ///  
        ///  
        ///  
        public static bool IsIdentityNumber(string num) 
        { 
            return Regex.IsMatch(num, @"^\d{17}[\d|X]|\d{15}$"); 
        } 
 
        ///  
        /// 检测是否符合邮编格式 
        ///  
        ///  
        ///  
        public static bool IsPostCode(string postCode) 
        { 
            return Regex.IsMatch(postCode, @"^\d{6}$"); 
        } 
 
 
        ///  
        /// MD5函数 
        ///  
        /// 原始字符串 
        /// MD5结果 
        public static string MD5(string str) 
        { 
            byte[] b = Encoding.Default.GetBytes(str); 
            b = new MD5CryptoServiceProvider().ComputeHash(b); 
            string ret = ""; 
            for (int i = 0; i < b.Length; i++) 
                ret += b[i].ToString("x").PadLeft(2, '0'); 
            return ret; 
        } 
 
 
 
        ///  
        /// 转换为简体中文 
        ///  
        public static string ToSChinese(string str) 
        { 
            return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0); 
        } 
 
        ///  
        /// 转换为繁体中文 
        ///  
        public static string ToTChinese(string str) 
        { 
            return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0); 
        } 
 
        ///  
        /// 自定义的替换字符串函数 
        ///  
        public static string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive) 
        { 
            return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None); 
        } 
 
        ///  
        /// 检查一个数组中所有的元素是否有包含于指定字符串的元素 
        ///  
        /// 存储数据数据的字串 
        /// 要查找的字符串 
        /// 数组的分隔符 
        ///  
        public static bool FoundStringInArr(string arr, string toFind, char separator) 
        { 
            if (arr.IndexOf(separator) >= 0) 
            { 
                string[] arrTemp = arr.Split('|'); 
                for (int i = 0; i < arrTemp.Length; i++) 
                { 
                    if ( ( toFind.ToLower().IndexOf( arrTemp[i].ToLower() ) >= 0) && (arrTemp[i].ToLower() != "")) 
                        return true; 
                } 
 
            } 
            else 
            { 
                if ( ( toFind.ToLower().IndexOf(arr.ToLower()) ) >= 0 && (arr.ToLower()!="")) 
                    return true; 
            } 
            return false; 
        } 
 
 
        #endregion  
 
        #region Sql类 
 
        ///  
        /// 检测是否有Sql危险字符 
        ///  
        /// 要判断字符串 
        /// 判断结果 
        public static bool IsSafeSqlString(string str) 
        { 
 
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); 
        } 
 
        ///  
        /// 改正sql语句中的转义字符 
        ///  
        public static string mashSQL(string str) 
        { 
            string str2; 
 
            if (str == null) 
            { 
                str2 = ""; 
            } 
            else 
            { 
                str = str.Replace("\'", "'"); 
                str2 = str; 
            } 
            return str2; 
        } 
 
        ///  
        /// 替换sql语句中的有问题符号 
        ///  
        public static string ReplaceBadSQL(string str) 
        { 
            string str2; 
 
            if (str == null) 
            { 
                str2 = ""; 
            } 
            else 
            { 
                str = str.Replace("'", "''"); 
                str2 = str; 
            } 
            return str2; 
        } 
 
 
 
        #endregion 
 
        #region Html类 
 
        ///  
        /// 返回 HTML 字符串的编码结果 
        ///  
        /// 字符串 
        /// 编码结果 
        public static string HtmlEncode(string str) 
        { 
           // str = str.Replace("'", "''"); 
            return HttpUtility.HtmlEncode(str); 
 
        } 
 
        ///  
        /// 返回 HTML 字符串的解码结果 
        ///  
        /// 字符串 
        /// 解码结果 
        public static string HtmlDecode(string str) 
        { 
            //str = str.Replace("''", "'"); 
            return HttpUtility.HtmlDecode(str); 
        } 
 
        ///  
        /// 替换html字符 
        ///  
        public static string EncodeHtml(string strHtml) 
        { 
            if (strHtml != "") 
            { 
                strHtml = strHtml.Replace(",", "&def"); 
                strHtml = strHtml.Replace("'", "&dot"); 
                strHtml = strHtml.Replace(";", "&dec"); 
                return strHtml; 
            } 
            return ""; 
        } 
 
        ///  
        /// 替换回车换行符为html换行符 
        ///  
        public static string StrFormat(string str) 
        { 
            string str2; 
 
            if (str == null) 
            { 
                str2 = ""; 
            } 
            else 
            { 
                str = str.Replace("\r\n", "
"); str = str.Replace("\n", "
"); str2 = str; } return str2; } #endregion #region DateTime类 /// /// 返回标准日期格式string /// public static string GetDate() { return DateTime.Now.ToString("yyyy-MM-dd"); } /// /// 返回指定日期格式 /// public static string GetDate(string datetimestr, string replacestr) { if (datetimestr == null) { return replacestr; } if (datetimestr.Equals("")) { return replacestr; } try { datetimestr = Convert.ToDateTime(datetimestr).ToString("yyyy-MM-dd").Replace("1900-01-01", replacestr); } catch { return replacestr; } return datetimestr; } /// /// 返回标准时间格式string /// public static string GetTime() { return DateTime.Now.ToString("HH:mm:ss"); } /// /// 返回标准时间格式string /// public static string GetDateTime() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } /// /// 返回相对于当前时间的相对天数 /// public static string GetDateTime(int relativeday) { return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss"); } /// /// 返回标准时间格式string /// public static string GetDateTimeF() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff"); } /// /// 返回标准时间 /// public static string GetStandardDateTime(string fDateTime, string formatStr) { DateTime s = Convert.ToDateTime(fDateTime); return s.ToString(formatStr); } /// /// 返回标准时间 yyyy-MM-dd HH:mm:ss /// public static string GetStandardDateTime(string fDateTime) { return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss"); } /// /// 返回相差的秒数 /// /// /// /// public static int StrDateDiffSeconds(string Time, int Sec) { TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec); if (ts.TotalSeconds > int.MaxValue) { return int.MaxValue; } else if (ts.TotalSeconds < int.MinValue) { return int.MinValue; } return (int)ts.TotalSeconds; } /// /// 返回相差的分钟数 /// /// /// /// public static int StrDateDiffMinutes(string time, int minutes) { if (time == "" || time == null) return 1; TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes); if (ts.TotalMinutes > int.MaxValue) { return int.MaxValue; } else if (ts.TotalMinutes < int.MinValue) { return int.MinValue; } return (int)ts.TotalMinutes; } /// /// 返回相差的小时数 /// /// /// /// public static int StrDateDiffHours(string time, int hours) { if (time == "" || time == null) return 1; TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours); if (ts.TotalHours > int.MaxValue) { return int.MaxValue; } else if (ts.TotalHours < int.MinValue) { return int.MinValue; } return (int)ts.TotalHours; } #endregion #region file类 /// /// 得到网站的真实路径 /// /// public static string GetTrueWebSitePath() { string path = HttpContext.Current.Request.Path; if (path.LastIndexOf("/") != path.IndexOf("/")) { path = path.Substring(path.IndexOf("/"), path.LastIndexOf("/") + 1); } else { path = "/"; } return path; } /// /// 文件是否存在 /// /// 相对路径 /// public static bool FileExists(string filePath) { if (string.IsNullOrEmpty(filePath)) return false; filePath = HttpContext.Current.Server.MapPath(filePath); DirectoryInfo dirInfo = new DirectoryInfo(filePath); if (dirInfo.Exists) return true; return false; } /// /// 创建目录 /// /// 相对路径 /// 是否成功 public static bool CreateDirectory(string filePath) { if (string.IsNullOrEmpty(filePath)) return false; filePath = HttpContext.Current.Server.MapPath(filePath); DirectoryInfo dirInfo = new DirectoryInfo(filePath); if (dirInfo.Exists) return true; try { Directory.CreateDirectory(filePath); return true; } catch { return false; } } #endregion #region Number类 /// /// 将long型数值转换为Int32类型 /// /// /// public static int SafeInt32(object objNum) { if (objNum == null) { return 0; } string strNum = objNum.ToString(); if (IsNumber(strNum)) { if (strNum.ToString().Length > 9) { return int.MaxValue; } return Int32.Parse(strNum); } else { return 0; } } #endregion } }