字符串辅助类代码
public class StringChange { /// <summary> /// 生成Token值 /// </summary> /// <returns></returns> static public string GetToken() { return Guid.NewGuid().ToString("N"); } /// <summary> /// 获取日期是一周中第几天 /// </summary> /// <param name="weekName"></param> /// <returns></returns> static public int DayOfWeek(DateTime dtime) { int week = 1; switch (dtime.DayOfWeek.ToString()) { case "Monday": week = 0; break; case "Tuesday": week = 1; break; case "Wednesday": week = 2; break; case "Thursday": week = 3; break; case "Friday": week = 4; break; case "Saturday": week = 5; break; case "Sunday": week = 6; break; } return week; } /// <summary> /// 是否是用户名 /// </summary> /// <param name="username"></param> /// <returns></returns> public static bool IsUserName(string username) { return Regex.IsMatch(username, @"^\w+$"); } public static string StrHtmlEncode(string str) { return System.Web.HttpContext.Current.Server.HtmlEncode(str); } /// <summary> /// 截取中英文混合字符串 /// </summary> /// <param name="original">原始字符串</param> /// <param name="length">截取长度</param> /// <param name="fill">截取串小于原始串时,尾部附加字符串</param> /// <returns></returns> public static string CutString(string original, int length, string fill) { Regex CnRegex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled); Char[] CharArray = original.ToCharArray(); int tmplength = 0; for (int i = 0; i < CharArray.Length; i++) { tmplength += CnRegex.IsMatch(CharArray[i].ToString()) ? 2 : 1; if (tmplength > length) { return original.Substring(0, i) + fill; } } return original; } /// <summary> /// 获得某个字符串在另个字符串最后一次出现时后面所有字符 /// </summary> /// <param name="strOriginal">要处理字符</param> /// <param name="strSymbol">符号</param> /// <returns>返回值</returns> public static string GetLastStr(string strOriginal, string strSymbol) { int strPlace = strOriginal.LastIndexOf(strSymbol) + strSymbol.Length; strOriginal = strOriginal.Substring(strPlace); return strOriginal; } /// <summary> /// 获得14时间+。。。位的时间随机数 /// </summary> /// <returns></returns> public static string GetDateRandom(int int_Count) { string strData = DateTime.Now.ToString(); strData = strData.Replace(":", ""); strData = strData.Replace("-", ""); strData = strData.Replace(" ", ""); strData = strData.Replace("/", ""); strData = strData + GetRandom(int_Count); return strData; } public static string GetRandom(int int_Count) { string str_RV = "1"; for (int i = 0; i < int_Count - 2; i++) { str_RV = str_RV + "0"; } Random r = new Random(); str_RV = r.Next(int.Parse(str_RV)).ToString(); int int_Count1 = int_Count - str_RV.Length; if (int_Count1 > 0) { for (int i = 0; i < int_Count1; i++) { str_RV = "0" + str_RV; } } return str_RV; } public static string GetRandomMix(int len) { int number; char code; string checkCode = String.Empty; System.Random random = new Random(); for (int i = 0; i < len; i++) { number = random.Next(); if (number % 2 == 0) code = (char)('0' + (char)(number % 10)); else code = (char)('A' + (char)(number % 26)); checkCode += code.ToString(); } return checkCode; } /// <summary> /// 获得拼音 /// </summary> /// <param name="str_Spell">汉字</param> /// <returns></returns> public string GetSpellByChinese(string str_Spell) { Hashtable t = hb(); byte[] b = System.Text.Encoding.Default.GetBytes(str_Spell); int p; StringBuilder ret = new StringBuilder(); for (int i = 0; i < b.Length; i++) { p = (int)b[i]; if (p > 160) { p = p * 256 + b[++i] - 65536; ret.Append(g(t, p)); } else { ret.Append((char)p); } } t.Clear(); return ret.ToString(); } private static string g(Hashtable ht, int num) { if (num < -20319 || num > -10247) return ""; while (!ht.ContainsKey(num)) num--; return ht[num].ToString(); } private static Hashtable hb() { Hashtable ht = new Hashtable(); ht.Add(-20319, "a"); ht.Add(-20317, "ai"); ht.Add(-20304, "an"); ht.Add(-20295, "ang"); ht.Add(-20292, "ao"); ht.Add(-20283, "ba"); ht.Add(-20265, "bai"); ht.Add(-20257, "ban"); ht.Add(-20242, "bang"); ht.Add(-20230, "bao"); ht.Add(-20051, "bei"); ht.Add(-20036, "ben"); ht.Add(-20032, "beng"); ht.Add(-20026, "bi"); ht.Add(-20002, "bian"); ht.Add(-19990, "biao"); ht.Add(-19986, "bie"); ht.Add(-19982, "bin"); ht.Add(-19976, "bing"); ht.Add(-19805, "bo"); ht.Add(-19784, "bu"); ht.Add(-19775, "ca"); ht.Add(-19774, "cai"); ht.Add(-19763, "can"); ht.Add(-19756, "cang"); ht.Add(-19751, "cao"); ht.Add(-19746, "ce"); ht.Add(-19741, "ceng"); ht.Add(-19739, "cha"); ht.Add(-19728, "chai"); ht.Add(-19725, "chan"); ht.Add(-19715, "chang"); ht.Add(-19540, "chao"); ht.Add(-19531, "che"); ht.Add(-19525, "chen"); ht.Add(-19515, "cheng"); ht.Add(-19500, "chi"); ht.Add(-19484, "chong"); ht.Add(-19479, "chou"); ht.Add(-19467, "chu"); ht.Add(-19289, "chuai"); ht.Add(-19288, "chuan"); ht.Add(-19281, "chuang"); ht.Add(-19275, "chui"); ht.Add(-19270, "chun"); ht.Add(-19263, "chuo"); ht.Add(-19261, "ci"); ht.Add(-19249, "cong"); ht.Add(-19243, "cou"); ht.Add(-19242, "cu"); ht.Add(-19238, "cuan"); ht.Add(-19235, "cui"); ht.Add(-19227, "cun"); ht.Add(-19224, "cuo"); ht.Add(-19218, "da"); ht.Add(-19212, "dai"); ht.Add(-19038, "dan"); ht.Add(-19023, "dang"); ht.Add(-19018, "dao"); ht.Add(-19006, "de"); ht.Add(-19003, "deng"); ht.Add(-18996, "di"); ht.Add(-18977, "dian"); ht.Add(-18961, "diao"); ht.Add(-18952, "die"); ht.Add(-18783, "ding"); ht.Add(-18774, "diu"); ht.Add(-18773, "dong"); ht.Add(-18763, "dou"); ht.Add(-18756, "du"); ht.Add(-18741, "duan"); ht.Add(-18735, "dui"); ht.Add(-18731, "dun"); ht.Add(-18722, "duo"); ht.Add(-18710, "e"); ht.Add(-18697, "en"); ht.Add(-18696, "er"); ht.Add(-18526, "fa"); ht.Add(-18518, "fan"); ht.Add(-18501, "fang"); ht.Add(-18490, "fei"); ht.Add(-18478, "fen"); ht.Add(-18463, "feng"); ht.Add(-18448, "fo"); ht.Add(-18447, "fou"); ht.Add(-18446, "fu"); ht.Add(-18239, "ga"); ht.Add(-18237, "gai"); ht.Add(-18231, "gan"); ht.Add(-18220, "gang"); ht.Add(-18211, "gao"); ht.Add(-18201, "ge"); ht.Add(-18184, "gei"); ht.Add(-18183, "gen"); ht.Add(-18181, "geng"); ht.Add(-18012, "gong"); ht.Add(-17997, "gou"); ht.Add(-17988, "gu"); ht.Add(-17970, "gua"); ht.Add(-17964, "guai"); ht.Add(-17961, "guan"); ht.Add(-17950, "guang"); ht.Add(-17947, "gui"); ht.Add(-17931, "gun"); ht.Add(-17928, "guo"); ht.Add(-17922, "ha"); ht.Add(-17759, "hai"); ht.Add(-17752, "han"); ht.Add(-17733, "hang"); ht.Add(-17730, "hao"); ht.Add(-17721, "he"); ht.Add(-17703, "hei"); ht.Add(-17701, "hen"); ht.Add(-17697, "heng"); ht.Add(-17692, "hong"); ht.Add(-17683, "hou"); ht.Add(-17676, "hu"); ht.Add(-17496, "hua"); ht.Add(-17487, "huai"); ht.Add(-17482, "huan"); ht.Add(-17468, "huang"); ht.Add(-17454, "hui"); ht.Add(-17433, "hun"); ht.Add(-17427, "huo"); ht.Add(-17417, "ji"); ht.Add(-17202, "jia"); ht.Add(-17185, "jian"); ht.Add(-16983, "jiang"); ht.Add(-16970, "jiao"); ht.Add(-16942, "jie"); ht.Add(-16915, "jin"); ht.Add(-16733, "jing"); ht.Add(-16708, "jiong"); ht.Add(-16706, "jiu"); ht.Add(-16689, "ju"); ht.Add(-16664, "juan"); ht.Add(-16657, "jue"); ht.Add(-16647, "jun"); ht.Add(-16474, "ka"); ht.Add(-16470, "kai"); ht.Add(-16465, "kan"); ht.Add(-16459, "kang"); ht.Add(-16452, "kao"); ht.Add(-16448, "ke"); ht.Add(-16433, "ken"); ht.Add(-16429, "keng"); ht.Add(-16427, "kong"); ht.Add(-16423, "kou"); ht.Add(-16419, "ku"); ht.Add(-16412, "kua"); ht.Add(-16407, "kuai"); ht.Add(-16403, "kuan"); ht.Add(-16401, "kuang"); ht.Add(-16393, "kui"); ht.Add(-16220, "kun"); ht.Add(-16216, "kuo"); ht.Add(-16212, "la"); ht.Add(-16205, "lai"); ht.Add(-16202, "lan"); ht.Add(-16187, "lang"); ht.Add(-16180, "lao"); ht.Add(-16171, "le"); ht.Add(-16169, "lei"); ht.Add(-16158, "leng"); ht.Add(-16155, "li"); ht.Add(-15959, "lia"); ht.Add(-15958, "lian"); ht.Add(-15944, "liang"); ht.Add(-15933, "liao"); ht.Add(-15920, "lie"); ht.Add(-15915, "lin"); ht.Add(-15903, "ling"); ht.Add(-15889, "liu"); ht.Add(-15878, "long"); ht.Add(-15707, "lou"); ht.Add(-15701, "lu"); ht.Add(-15681, "lv"); ht.Add(-15667, "luan"); ht.Add(-15661, "lue"); ht.Add(-15659, "lun"); ht.Add(-15652, "luo"); ht.Add(-15640, "ma"); ht.Add(-15631, "mai"); ht.Add(-15625, "man"); ht.Add(-15454, "mang"); ht.Add(-15448, "mao"); ht.Add(-15436, "me"); ht.Add(-15435, "mei"); ht.Add(-15419, "men"); ht.Add(-15416, "meng"); ht.Add(-15408, "mi"); ht.Add(-15394, "mian"); ht.Add(-15385, "miao"); ht.Add(-15377, "mie"); ht.Add(-15375, "min"); ht.Add(-15369, "ming"); ht.Add(-15363, "miu"); ht.Add(-15362, "mo"); ht.Add(-15183, "mou"); ht.Add(-15180, "mu"); ht.Add(-15165, "na"); ht.Add(-15158, "nai"); ht.Add(-15153, "nan"); ht.Add(-15150, "nang"); ht.Add(-15149, "nao"); ht.Add(-15144, "ne"); ht.Add(-15143, "nei"); ht.Add(-15141, "nen"); ht.Add(-15140, "neng"); ht.Add(-15139, "ni"); ht.Add(-15128, "nian"); ht.Add(-15121, "niang"); ht.Add(-15119, "niao"); ht.Add(-15117, "nie"); ht.Add(-15110, "nin"); ht.Add(-15109, "ning"); ht.Add(-14941, "niu"); ht.Add(-14937, "nong"); ht.Add(-14933, "nu"); ht.Add(-14930, "nv"); ht.Add(-14929, "nuan"); ht.Add(-14928, "nue"); ht.Add(-14926, "nuo"); ht.Add(-14922, "o"); ht.Add(-14921, "ou"); ht.Add(-14914, "pa"); ht.Add(-14908, "pai"); ht.Add(-14902, "pan"); ht.Add(-14894, "pang"); ht.Add(-14889, "pao"); ht.Add(-14882, "pei"); ht.Add(-14873, "pen"); ht.Add(-14871, "peng"); ht.Add(-14857, "pi"); ht.Add(-14678, "pian"); ht.Add(-14674, "piao"); ht.Add(-14670, "pie"); ht.Add(-14668, "pin"); ht.Add(-14663, "ping"); ht.Add(-14654, "po"); ht.Add(-14645, "pu"); ht.Add(-14630, "qi"); ht.Add(-14594, "qia"); ht.Add(-14429, "qian"); ht.Add(-14407, "qiang"); ht.Add(-14399, "qiao"); ht.Add(-14384, "qie"); ht.Add(-14379, "qin"); ht.Add(-14368, "qing"); ht.Add(-14355, "qiong"); ht.Add(-14353, "qiu"); ht.Add(-14345, "qu"); ht.Add(-14170, "quan"); ht.Add(-14159, "que"); ht.Add(-14151, "qun"); ht.Add(-14149, "ran"); ht.Add(-14145, "rang"); ht.Add(-14140, "rao"); ht.Add(-14137, "re"); ht.Add(-14135, "ren"); ht.Add(-14125, "reng"); ht.Add(-14123, "ri"); ht.Add(-14122, "rong"); ht.Add(-14112, "rou"); ht.Add(-14109, "ru"); ht.Add(-14099, "ruan"); ht.Add(-14097, "rui"); ht.Add(-14094, "run"); ht.Add(-14092, "ruo"); ht.Add(-14090, "sa"); ht.Add(-14087, "sai"); ht.Add(-14083, "san"); ht.Add(-13917, "sang"); ht.Add(-13914, "sao"); ht.Add(-13910, "se"); ht.Add(-13907, "sen"); ht.Add(-13906, "seng"); ht.Add(-13905, "sha"); ht.Add(-13896, "shai"); ht.Add(-13894, "shan"); ht.Add(-13878, "shang"); ht.Add(-13870, "shao"); ht.Add(-13859, "she"); ht.Add(-13847, "shen"); ht.Add(-13831, "sheng"); ht.Add(-13658, "shi"); ht.Add(-13611, "shou"); ht.Add(-13601, "shu"); ht.Add(-13406, "shua"); ht.Add(-13404, "shuai"); ht.Add(-13400, "shuan"); ht.Add(-13398, "shuang"); ht.Add(-13395, "shui"); ht.Add(-13391, "shun"); ht.Add(-13387, "shuo"); ht.Add(-13383, "si"); ht.Add(-13367, "song"); ht.Add(-13359, "sou"); ht.Add(-13356, "su"); ht.Add(-13343, "suan"); ht.Add(-13340, "sui"); ht.Add(-13329, "sun"); ht.Add(-13326, "suo"); ht.Add(-13318, "ta"); ht.Add(-13147, "tai"); ht.Add(-13138, "tan"); ht.Add(-13120, "tang"); ht.Add(-13107, "tao"); ht.Add(-13096, "te"); ht.Add(-13095, "teng"); ht.Add(-13091, "ti"); ht.Add(-13076, "tian"); ht.Add(-13068, "tiao"); ht.Add(-13063, "tie"); ht.Add(-13060, "ting"); ht.Add(-12888, "tong"); ht.Add(-12875, "tou"); ht.Add(-12871, "tu"); ht.Add(-12860, "tuan"); ht.Add(-12858, "tui"); ht.Add(-12852, "tun"); ht.Add(-12849, "tuo"); ht.Add(-12838, "wa"); ht.Add(-12831, "wai"); ht.Add(-12829, "wan"); ht.Add(-12812, "wang"); ht.Add(-12802, "wei"); ht.Add(-12607, "wen"); ht.Add(-12597, "weng"); ht.Add(-12594, "wo"); ht.Add(-12585, "wu"); ht.Add(-12556, "xi"); ht.Add(-12359, "xia"); ht.Add(-12346, "xian"); ht.Add(-12320, "xiang"); ht.Add(-12300, "xiao"); ht.Add(-12120, "xie"); ht.Add(-12099, "xin"); ht.Add(-12089, "xing"); ht.Add(-12074, "xiong"); ht.Add(-12067, "xiu"); ht.Add(-12058, "xu"); ht.Add(-12039, "xuan"); ht.Add(-11867, "xue"); ht.Add(-11861, "xun"); ht.Add(-11847, "ya"); ht.Add(-11831, "yan"); ht.Add(-11798, "yang"); ht.Add(-11781, "yao"); ht.Add(-11604, "ye"); ht.Add(-11589, "yi"); ht.Add(-11536, "yin"); ht.Add(-11358, "ying"); ht.Add(-11340, "yo"); ht.Add(-11339, "yong"); ht.Add(-11324, "you"); ht.Add(-11303, "yu"); ht.Add(-11097, "yuan"); ht.Add(-11077, "yue"); ht.Add(-11067, "yun"); ht.Add(-11055, "za"); ht.Add(-11052, "zai"); ht.Add(-11045, "zan"); ht.Add(-11041, "zang"); ht.Add(-11038, "zao"); ht.Add(-11024, "ze"); ht.Add(-11020, "zei"); ht.Add(-11019, "zen"); ht.Add(-11018, "zeng"); ht.Add(-11014, "zha"); ht.Add(-10838, "zhai"); ht.Add(-10832, "zhan"); ht.Add(-10815, "zhang"); ht.Add(-10800, "zhao"); ht.Add(-10790, "zhe"); ht.Add(-10780, "zhen"); ht.Add(-10764, "zheng"); ht.Add(-10587, "zhi"); ht.Add(-10544, "zhong"); ht.Add(-10533, "zhou"); ht.Add(-10519, "zhu"); ht.Add(-10331, "zhua"); ht.Add(-10329, "zhuai"); ht.Add(-10328, "zhuan"); ht.Add(-10322, "zhuang"); ht.Add(-10315, "zhui"); ht.Add(-10309, "zhun"); ht.Add(-10307, "zhuo"); ht.Add(-10296, "zi"); ht.Add(-10281, "zong"); ht.Add(-10274, "zou"); ht.Add(-10270, "zu"); ht.Add(-10262, "zuan"); ht.Add(-10260, "zui"); ht.Add(-10256, "zun"); ht.Add(-10254, "zuo"); ht.Add(-10247, "zz"); return ht; } public static string NoHTML(string Htmlstring) { //删除脚本 Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase); //删除HTML Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(ldquo|rdquo|mdash);", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase); Htmlstring.Replace("<", ""); Htmlstring.Replace(">", ""); Htmlstring.Replace("\r\n", ""); Htmlstring = System.Web.HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim(); return Htmlstring; } public static string SqlEncode(string strInput) { string str; try { str = strInput.Replace("'", "''"); } catch { str = "error"; } if (IsSafety(str)) { return str; } else { return "文本含有非法字符,已经被屏蔽!"; } } public static bool IsSafety(string str) { string text1 = str.Replace("%20", " "); text1 = Regex.Replace(text1, @"\s", " "); string text2 = "select |insert |delete from |count\\(|drop table|update |truncate |asc\\(|mid\\(|char\\(|xp_cmdshell|exec master|net localgroup administrators|:|net user|\"|\\'| or "; return !Regex.IsMatch(text1, text2, RegexOptions.IgnoreCase); } public static string SqlDecode(string strInput) { string str; try { str = strInput.Replace("''", "'"); } catch { str = "error"; } return str; } //字符转换成数据型 public static int StringToInt(string strInput) { int str = 0; try { str = Convert.ToInt32(strInput); } catch { str = 0; } return str; } public static long StringToLong(string strInput) { long str = 0; try { str = Convert.ToInt64(strInput); } catch { str = 0; } return str; } /// <summary> /// md5加密 /// </summary> /// <param name="key">需要加密的字段</param> /// <returns></returns> public static string Jm(string key) { return BitConverter.ToString(MD5.Create().ComputeHash(Encoding.Default.GetBytes(key))).Replace("-", "").ToLower(); //return FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").ToLower(); } /// <summary> /// 检测字符数组中是否包含某个字符串 /// </summary> /// <param name="xx">要检测的字符</param> /// <param name="xxx">被检测的字符数组</param> /// <returns></returns> public static bool IsContain(string xx, string[] xxx) { bool iscontain = false; for (int i = 0; i < xxx.Length; i++) { if (xxx[i] == xx) { iscontain = true; } } return iscontain; } /// <summary> /// 检测字符数组中是否 /// </summary> /// <param name="xx"></param> /// <param name="xxx"></param> /// <returns></returns> public static bool IsIntIt(string xx, string[] xxx) { bool iscontain = false; for (int i = 0; i < xxx.Length; i++) { if (xx.IndexOf(xxx[i]) > -1) { iscontain = true; } } return iscontain; } /// <summary> /// 获取IP /// </summary> /// <returns></returns> public static string GetIP() { string ipStr = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ipStr)) { ipStr = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } else { //ipStr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (ipStr.IndexOf(",") != -1) { //有“,”,估计多个代理。取第一个不是内网的IP。 ipStr = ipStr.Replace(" ", "").Replace("'", ""); string[] temparyip = ipStr.Split(",;".ToCharArray()); for (int i = 0; i < temparyip.Length; i++) { if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.") { ipStr = temparyip[i]; //找到不是内网的地址 break; } } } } return ipStr; } 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); } /// <summary> /// 获取url参数 /// </summary> /// <param name="sth">参数名</param> /// <returns></returns> public static string GetQuery(string sth) { if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[sth])) { return SqlFilter(HttpContext.Current.Request.QueryString[sth]); } else { return String.Empty; } } public static string GetQueryForm(string sth) { if (!String.IsNullOrEmpty(HttpContext.Current.Request.Form[sth])) { return SqlFilter(HttpContext.Current.Request.Form[sth]); } else { return String.Empty; } } public static string GetQueryUntreated(string sth) { if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[sth])) { return HttpContext.Current.Request.QueryString[sth]; } else { return String.Empty; } } //public static string GetQuery(string sth,bool b1) //{ // if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[sth])) // { // return SqlFilter(HttpContext.Current.Request.QueryString[sth]); // } // else // { // return String.Empty; // } //} public static string GetQuery(string key, Encoding encoding) { //引用System.Collections.Specialized和System.Text命名空间 //string stringValue; System.Collections.Specialized.NameValueCollection encodingQueryString; //该方法是在2.0中新增的 encodingQueryString = HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query, encoding); //'里面的key就是你提交的参数的Key return encodingQueryString[key] != null ? encodingQueryString[key].Trim() : ""; } /// 增加字符串 /// </summary> /// <param name="strLong"></param> /// <param name="str"></param> /// <returns></returns> public static string StringOfChar(int strLong, string str) { string ReturnStr = ""; for (int i = 0; i < strLong; i++) { ReturnStr += str; } return ReturnStr; } /// <summary> /// 十进制转成4位二进制 /// </summary> /// <param name="ten"></param> /// <param name="two"></param> /// <returns></returns> public static string TenToTwo(int ten) { string x = Convert.ToString(ten, 2); char[] xx = x.ToCharArray(); int bw = 4 - xx.Length; string xxx = StringOfChar(bw, "0") + x; return xxx; } /// <summary> /// 将字符串数组转成字符串 /// </summary> /// <param name="strArray">字符串数组</param> /// <param name="Separator">分隔符</param> /// <returns>字符串</returns> public static string StringArrayToString(string[] strArray, char Separator) { string str = string.Empty; for (int i = 0; i < strArray.Length; i++) { str = str + strArray[i] + Separator; } return str.Substring(0, str.Length - 1); } public static string MinToHours(int minutes) { return (minutes / 3600 + "小时" + minutes % 60 + "分").ToString(); } /// <summary> /// 检测是否符合email格式 /// </summary> /// <param name="strEmail">要判断的email字符串</param> /// <returns>判断结果</returns> public static bool IsValidEmail(string strEmail) { return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]"); } /// <summary> /// 检查是否是数字 /// </summary> /// <returns></returns> public static bool IsNum(string strNum) { return Regex.IsMatch(strNum, @"^[0-9]"); } /// <summary> /// 过滤HTML中的不安全标签 /// </summary> /// <param name="content"></param> /// <returns></returns> public static string RemoveUnsafeHtml(string content) { content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase); content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase); return content; } /// <summary> /// 移除Html标记 /// </summary> /// <param name="content"></param> /// <returns></returns> public static string RemoveHtml(string content) { return Regex.Replace(content, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase); } /// <summary> /// 检测是否有Sql危险字符 /// </summary> /// <param name="str">要判断字符串</param> /// <returns>判断结果</returns> public static bool IsSafeSqlString(string str) { return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); } public static bool IsValidDoEmail(string strEmail) { return Regex.IsMatch(strEmail, @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } /// <summary> /// 检测是否是正确的Url /// </summary> /// <param name="strUrl">要验证的Url</param> /// <returns>判断结果</returns> public static bool IsURL(string strUrl) { return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); } public static string GetEmailHostName(string strEmail) { if (strEmail.IndexOf("@") < 0) { return ""; } return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower(); } /// <summary> /// 判断是否为base64字符串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsBase64String(string str) { //A-Z, a-z, 0-9, +, /, = return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]"); } /// <summary> /// unix时间转成系统时间 /// </summary> /// <param name="timeStamp"></param> /// <returns></returns> public static DateTime UnixTimeToWindows(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } public static bool match(string emailInput) { string emailFormat = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"; bool boolean = Regex.IsMatch(emailInput, emailFormat); return boolean; } public static string setidno(string idno) { StringBuilder sb = new StringBuilder(); sb.Append(idno.Substring(0, 3)); for (int i = 0; i < idno.Length - 7; i++) { sb.Append("*"); } sb.Append(idno.Substring(idno.Length - 4)); return sb.ToString(); } public static string setmail(string email) { if (!string.IsNullOrEmpty(email)) { if (email.Contains("@")) { StringBuilder sb = new StringBuilder(); string[] message = email.Split('@'); if (message[0].Length > 3) { sb.Append(message[0].Substring(0, 2)); for (int i = 0; i < message[0].Length - 2 - 1; i++) { sb.Append("*"); } sb.Append(message[0].Substring(message[0].Length - 1)); } //修改1 else if (message[0].Length >= 1) { sb.Append(message[0].Substring(0, 1)); for (int i = 0; i < message[0].Length - 1; i++) { sb.Append("*"); } } sb.Append("@"); sb.Append(message[1]); return sb.ToString(); } else { return email; } } else { return ""; } } /// <summary> /// 对ip进行限制访问 /// </summary> //public static void CheckAccessWeb() //{ // string testip = DBHelper.testip; // string url = HttpContext.Current.Request.Url.ToString(); // string hostName = Dns.GetHostName(); // IPAddress[] addresslist = Dns.GetHostByName(hostName).AddressList; // string ip = addresslist.GetValue(0).ToString(); // string fromip = StringChange.GetIP(); // //不开放的 // string[] xx = new string[] { "jianghu" }; // //来访地址 // string[] yy = new string[] { "127.0.0.1", testip }; // bool ishave = StringChange.IsIntIt(url.ToLower(), xx); // bool isip = StringChange.IsIntIt(fromip.ToString(), yy); // if (ip != "192.168.2.102") // { // if (ishave == true && isip == false) // { // HttpContext.Current.Response.Redirect(DBHelper.hostName + "404.aspx"); // } // } // //if (ip != "192.168.2.102") // //{ // // if (ishave == true && isip == false) // // { // // HttpContext.Current.Response.Redirect(DBHelper.hostName + "404.aspx"); // // } // //} //} /// <summary> /// 返回不重复的随机数,start和end表示随机的范围,count表示返回的数量 /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <param name="count"></param> /// <returns></returns> public static int[] GenerateNumber(int start, int end, int count) { //用于存放start-end范围的数组 int[] container = new int[end - start]; //用于保存返回结果 int[] result = new int[count]; Random random = new Random(); for (int i = start; i <= end; i++) { container[i - 1] = i; } int index = 0; int value = 0; for (int i = 0; i < count; i++) { //从[1,container.Count + 1)中取一个随机值,保证这个值不会超过container的元素个数 index = random.Next(1, container.Length - 1 - i); //以随机生成的值作为索引取container中的值 value = container[index]; //将随机取得值的放到结果集合中 result[i] = value; //将刚刚使用到的从容器集合中移到末尾去 container[index] = container[container.Length - i - 1]; //将刚使用过的随机数放到container数组末,因为下一次循环不可能用到,保证了取数的唯一性 container[container.Length - i - 1] = value; } return result; } public static string GetModuleUrl() { string url = HttpContext.Current.Request.Url.LocalPath; url = url.Substring(1); string[] param = HttpContext.Current.Request.QueryString.AllKeys; bool temp = false; for (int i = 0; i < param.Length; i++) { if (param[i] == "from") { temp = true; } } if (param.Length > 0) { if (param[0] != "from" && temp)//原来的写法是if (param[0] != "from"&&temp),不知道啥意思,直接干掉temp! { url += "?" + param[0]; } } return url; } /// <summary> /// 返回四位随机数 /// </summary> /// <returns></returns> public static string RandomCode_bak() { Random random = new Random(); return random.Next(1000, 9999).ToString(); } /// <summary> /// 判断混合字符串长度 /// </summary> /// <param name="str"></param> /// <returns></returns> public static int StrLength(string str) { int len = 0; byte[] b; for (int i = 0; i < str.Length; i++) { b = Encoding.Default.GetBytes(str.Substring(i, 1)); if (b.Length > 1) len += 2; else len++; } return len; } //public static bool IsBadwords(string w) //{ // bool rv = false; // string[] words = Long.Utils.FilesControl.ReadFile("/badwords.txt").Split(','); // foreach (string temp in words) // { // if (w.Contains(temp)) // { // if (temp == "") break; // rv = true; // break; // } // } // return rv; //} #region 判断字符串是否某类型 /// <summary> /// 是否为日期型字符串 /// </summary> /// <param name="StrSource">日期字符串(2008-05-08)</param> /// <returns></returns> public static bool IsDate(string StrSource) { return Regex.IsMatch(StrSource, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]" + @"|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|" + @"1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?" + @"2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468]" + @"[048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$"); //^((((1[6-9]|[2-9]\d)\d{2})[-/](0?[13578]|1[02])[-/](0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$ } /// <summary> /// 是否为日期+时间型字符串 2025/10/17 10:02:09 2025-10-17 10:02:09 /// </summary> /// <param name="source"></param> /// <returns></returns> public static bool IsDateTime(string StrSource) { return Regex.IsMatch(StrSource, @"^(?:(?!0000)[0-9]{4}([-/.]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]?)0?2\2(?:29))\s+([01]*[0-9]|2[0-3]):[0-5]*[0-9]:[0-5]*[0-9]$"); } public static bool IsNum_bak(string str) { System.Text.RegularExpressions.Regex regNum = new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$"); return regNum.IsMatch(str); } public static bool IsDecimal(string str) { System.Text.RegularExpressions.Regex regNum = new System.Text.RegularExpressions.Regex("^([0-9]+)$|^([0-9]+[.]{0,1}[0-9]+)$"); return regNum.IsMatch(str); } /// <summary> /// 判断是否整数 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsInt(string str) { if (str == "") return false; System.Text.RegularExpressions.Regex regNum = new System.Text.RegularExpressions.Regex("^[0-9]*$"); return regNum.IsMatch(str); } /// <summary> /// 判断是否正整数 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsIntPositive(string str) { return IsInt(str) && Convert.ToInt32(str) > 0; } #endregion public static string StarStr(object s) { string rv = ""; int i = 0; foreach (char c in s.ToString().ToCharArray()) { if (i++ == 0 || i == (s.ToString().Length)) { rv += c; } else { rv += '*'; } } return rv; } #region 删除最后结尾的指定字符后的字符 /// <summary> /// 删除最后结尾的指定字符后的字符 /// </summary> public static string DelLastChar(string str, string strchar) { if (string.IsNullOrEmpty(str)) return ""; if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1) { return str.Substring(0, str.LastIndexOf(strchar)); } return str; } #endregion /// <summary> /// URL字符编码 /// </summary> public static string UrlEncode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } str = str.Replace("'", ""); return HttpContext.Current.Server.UrlEncode(str); } /// <summary> /// 执行URL获取页面内容 /// </summary> public static string UrlExecute(string urlPath) { if (string.IsNullOrEmpty(urlPath)) { return "error"; } StringWriter sw = new StringWriter(); try { HttpContext.Current.Server.Execute(urlPath, sw); return sw.ToString(); } catch (Exception ex) { return "error" + ex.Message; } finally { sw.Close(); sw.Dispose(); } } #region 过滤 Sql 语句字符串中的注入脚本 /// <summary> /// 过滤 Sql 语句字符串中的注入脚本 /// </summary> /// <param name="source">传入的字符串</param> /// <returns>过滤后的字符串</returns> public static string SqlFilter(string source) { source = source.Replace("'", ""); source = source.Replace("\"", ""); source = source.Replace("&", "&"); source = source.Replace("<", "<"); source = source.Replace(">", ">"); source = source.Replace("delete", ""); source = source.Replace("update", ""); source = source.Replace("insert", ""); //单引号替换成两个单引号 source = source.Replace("'", "''"); //半角封号替换为全角封号,防止多语句执行 source = source.Replace(";", ";"); //半角括号替换为全角括号 source = source.Replace("(", "("); source = source.Replace(")", ")"); ///////////////要用正则表达式替换,防止字母大小写得情况//////////////////// //去除执行存储过程的命令关键字 source = source.Replace("Exec", ""); source = source.Replace("Execute", ""); //去除系统存储过程或扩展存储过程关键字 source = source.Replace("xp_", "x p_"); source = source.Replace("sp_", "s p_"); //防止16进制注入 source = source.Replace("0x", "0 x"); return source; } #endregion /// <summary> /// unix时间转换为datetime /// </summary> /// <param name="timeStamp"></param> /// <returns></returns> public static DateTime UnixTimeToTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } /// <summary> /// datetime转换为unixtime /// </summary> /// <param name="time"></param> /// <returns></returns> public static int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } public static string GetWeekMonday(System.DayOfWeek dw, string timeFormateStr) { int weeknow = Convert.ToInt32(dw); int mondayNum = (-1) * weeknow + 1; string weekMonday = System.DateTime.Now.AddDays(mondayNum).Date.ToString(timeFormateStr); return weekMonday; } }