12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859 |
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Web;
- using System.Web.UI;
- using Microsoft.VisualBasic;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Net;
- using System.Net.Mail;
- using System.Linq;
- using System.Configuration;
- namespace CP.Common
- {
- /// <summary>
- /// 工具类
- /// </summary>
- public class Utils
- {
- #region 获取Int星期值
- /// <summary>
- /// 获取int星期值
- /// </summary>
- /// <param name="StrWeek"></param>
- /// <returns></returns>
- public static int GetIntWeek(string StrWeek)
- {
- int intWeekday = -1;
- switch (StrWeek)
- {
- case "Monday":
- intWeekday = 1;
- break;
- case "Tuesday":
- intWeekday = 2;
- break;
- case "Wednesday":
- intWeekday = 3;
- break;
- case "Thursday":
- intWeekday = 4;
- break;
- case "Friday":
- intWeekday = 5;
- break;
- case "Saturday":
- intWeekday = 6;
- break;
- case "Sunday":
- intWeekday = 7;
- break;
- default:
- intWeekday = -1;
- break;
- }
- return intWeekday;
- }
- #endregion
- /// <summary>
- /// 验证是否为整数,且大于min
- /// </summary>
- /// <param name="min"></param>
- /// <param name="judgeStr"></param>
- /// <returns></returns>
- public static bool JudgeInt(int min, string judgeStr)
- {
- if (string.IsNullOrWhiteSpace(judgeStr))
- return false;
- int value = 0;
- if (!int.TryParse(judgeStr, out value))
- return false;
- if (value < min)
- return false;
- return true;
- }
- /// <summary>
- /// 下期奖池、投注金额
- /// </summary>
- /// <param name="min"></param>
- /// <param name="judgeStr"></param>
- /// <returns></returns>
- public static bool JudgeLong(int min, string judgeStr)
- {
- if (string.IsNullOrWhiteSpace(judgeStr))
- return false;
- long value = 0;
- if (!long.TryParse(judgeStr, out value))
- return false;
- if (value < min)
- return false;
- return true;
- }
- public static bool JudgeInt(int min,int max, string judgeStr)
- {
- if (string.IsNullOrWhiteSpace(judgeStr))
- return false;
- int value = 0;
- if (!int.TryParse(judgeStr, out value))
- return false;
- if (value < min)
- return false;
- if (value > max)
- return false;
- return true;
- }
- public static bool JudgeIntWithLen2(int min, int max, string judgeStr)
- {
- if (string.IsNullOrWhiteSpace(judgeStr))
- return false;
- if (judgeStr.Length != 2)
- return false;
- int value = 0;
- if (!int.TryParse(judgeStr, out value))
- return false;
- if (value < min)
- return false;
- if (value > max)
- return false;
- return true;
- }
- /// <summary>
- /// 分析开奖号,组六0、组三2、豹子3
- /// </summary>
- /// <param name="kaijianghao"></param>
- /// <returns></returns>
- public static int StatisticKaijianghao(string kaijianghao)
- {
- if (kaijianghao[0] == kaijianghao[1] && kaijianghao[0] == kaijianghao[2])
- return 3;
- else if (kaijianghao[0] != kaijianghao[1] && kaijianghao[0] != kaijianghao[2] && kaijianghao[1] != kaijianghao[2])
- return 0;
- else return 2;
- }
- public static bool JudgeInt(string value)
- {
- int ret = 0;
- if (!int.TryParse(value, out ret))
- {
- return false;
- }
- return true;
- }
- /// <summary>
- /// 邮件发送程序
- /// </summary>
- /// <param name="mail"></param>
- /// <returns></returns>
- public static bool SendMail(MailMessage mail)
- {
- bool yes = false;
- mail.IsBodyHtml = true;
- mail.SubjectEncoding = System.Text.Encoding.GetEncoding("utf-8");
- SmtpClient smtpClient = new SmtpClient();
- smtpClient.EnableSsl = false;
- smtpClient.Host = "smtp.exmail.qq.com";
- smtpClient.Port = 25;
- smtpClient.Credentials = new NetworkCredential("8200@6617.com", "love0021$%");
- try
- {
- smtpClient.Send(mail);
- yes = true;
- }
- catch //(Exception ex)
- {
- //System.Web.HttpContext.Current.Response.Write(ex.Message );
- }
- return yes;
- }
- /// <summary>
- /// 生成永不重复的字串..
- /// 然后md5
- /// </summary>
- /// <returns></returns>
- public static string GetRandomString()
- {
- string key = System.Guid.NewGuid().ToString().Replace("-", "");
- return MD5(key);
- }
- /// <summary>
- /// 返回url的根域名
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string GetUrlDomainName(string url)
- {
- string p = @"^https?://(?<domain>[^/]+)(/|$)";
- Regex reg = new Regex(p, RegexOptions.IgnoreCase);
- Match m = reg.Match(url);
- return m.Groups["domain"].Value.ToString().Trim();
- }
- /// <summary>
- /// 取图片源地址string[]
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- public static string[] GetHtmlImageUrlList(string content)
- {
- // 定义正则表达式用来匹配 img 标签
- Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
- // 搜索匹配的字符串
- MatchCollection matches = regImg.Matches(content);
- int i = 0;
- string[] list = new string[matches.Count];
- // 取得匹配项列表
- foreach (Match match in matches)
- list[i++] = match.Groups["imgUrl"].Value.ToString().Trim();
- return list;
- }
- /// <summary>
- /// http post
- /// </summary>
- /// <param name="url"></param>
- /// <param name="param"></param>
- /// <returns></returns>
- public static string HttpPost(string url, string param)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
- request.Accept = "*/*";
- request.Timeout = 15000;
- request.AllowAutoRedirect = false;
- StreamWriter requestStream = null;
- WebResponse response = null;
- string responseStr = null;
- try
- {
- requestStream = new StreamWriter(request.GetRequestStream());
- requestStream.Write(param);
- requestStream.Close();
- response = request.GetResponse();
- if (response != null)
- {
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- }
- catch (Exception)
- {
- throw;
- }
- finally
- {
- request = null;
- if (requestStream != null)
- requestStream.Close();
- if (response != null)
- response.Close();
- }
- return responseStr;
- }
- /// <summary>
- /// HTTP Get请求
- /// </summary>
- /// <param name="url">地址</param>
- /// <returns></returns>
- public static string HttpGet(string url)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
- request.Method = "GET";
- request.ContentType = "application/x-www-form-urlencoded";
- request.Accept = "*/*";
- request.Timeout = 15000;
- request.ServicePoint.Expect100Continue = false;
- //request.AllowAutoRedirect = false;
- request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36";
- WebResponse response = null;
- string responseStr = string.Empty;
- try
- {
- response = request.GetResponse();
- if (response != null)
- {
- StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
- responseStr = reader.ReadToEnd();
- reader.Close();
- }
- }
- catch (WebException ex)
- {
- responseStr = "Http Get出错,出错信息:" + ex.Message;
- }
- finally
- {
- request = null;
- if (response != null)
- response.Close();
- }
- return responseStr;
- }
- /// <summary>
- /// 下载网络图片
- /// 返回二进制流
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static byte[] GetRemoteUrlByte(string url)
- {
- if (url.IndexOf("http://") == -1)
- {
- url = "http://pic.8200.cn/" + url;
- }
- byte[] bs = null;
- try
- {
- System.Net.WebClient wc = new System.Net.WebClient();
- bs = wc.DownloadData(url);
- }
- catch { }
- return bs;
- }
- /// <summary>
- /// 根据字符长度,返回n个*号
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string GetStar(string str)
- {
- int len = str.Length;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < len; i++)
- {
- sb.Append("*");
- }
- return sb.ToString();
- }
- /// <summary>
- /// 截取固定长度并不带html字串的方法
- /// </summary>
- /// <param name="str"></param>
- /// <param name="len"></param>
- /// <returns></returns>
- public static string GetCutNoHtmlString(string str, int len)
- {
- str = RemoveHtml(str);
- str = str.Replace("<br />", "");
- str = str.Replace("<br>", "");
- str = str.Replace("。", "");
- str = str.Replace(",", " ");
- str = str.Replace(",", " ");
- str = str.Replace("\r\n", "");
- str = str.Replace("\r", "");
- str = str.Replace("\n", "");
- str = str.Replace(" ", "");
- str = str.Replace(" ", " ");
- return CutString(str, len) + "...";
- }
- /// <summary>
- /// 算出数组中出现次数最多的 元素+次数
- /// 返回 7-3 格式
- /// </summary>
- /// <param name="array"></param>
- /// <returns></returns>
- public static string GetArrayMaxCount(object[] array)
- {
- if (array == null || array.Length == 0)
- return "";
- var groupList = array.ToList().GroupBy(a => a).Select(g => new { g.Key, count = g.Count() }).OrderByDescending(c => c.count);
- object maxNum = groupList.ToList()[0].Key;
- object maxValue = groupList.ToList()[0].count;
- return maxNum + "<span>(" + maxValue + ")</span>";
- }
- /// <summary>
- /// 构造出3d/p3的1000注所有号码
- /// </summary>
- /// <returns></returns>
- public static List<int> GetAllNumber()
- {
- List<int> list = new List<int>();
- for (int i = 0; i < 1000; i++)
- list.Add(i);
- return list;
- }
- /// <summary>
- /// 取站点的http://+domain部分..
- /// </summary>
- /// <returns></returns>
- public static string GetDomain()
- {
- string domain = "www.8200.cn";
- if (ConfigurationManager.AppSettings["domain"] != null)
- domain = ConfigurationManager.AppSettings["domain"].ToString().Trim();
- return "https://" + domain;
- //return "http://" + domain;
- }
- /// <summary>
- /// 读取某相对路径下的文本文件内容
- /// </summary>
- /// <param name="path">相对路径</param>
- /// <returns></returns>
- public static string ReadFile(string path)
- {
- string result = string.Empty;
- try
- {
- path = HttpContext.Current.Server.MapPath("/") + path;
- result = File.ReadAllText(path);
- }
- catch
- {
- throw;
- }
- return result;
- }
- /// <summary>
- /// 获得当前页面客户端的IP
- /// </summary>
- /// <returns>当前页面客户端的IP</returns>
- public static string GetRealIP()
- {
- string result = string.Empty;
- //result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
- //if (string.IsNullOrEmpty(result))
- result = HttpContext.Current.Request.ServerVariables["HTTP_CDN_SRC_IP"];
- if (string.IsNullOrEmpty(result))
- result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
- if (string.IsNullOrEmpty(result))
- result = HttpContext.Current.Request.UserHostAddress;
- if (string.IsNullOrEmpty(result) || !IsIP(result))
- return "127.0.0.1";
- return result;
- }
- /// <summary>
- /// 写Cookie值
- /// </summary>
- /// <param name="strName">键</param>
- /// <param name="strValue">名</param>
- /// <param name="httponly">httponly默认true</param>
- /// <param name="expires">默认480分钟</param>
- public static void WriteCookie(string strName, string strValue, int expires = 480, bool httponly = true)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.HttpOnly = httponly;
- //cookie.Domain = ".8200.cn";
- cookie.Value = HttpContext.Current.Server.UrlEncode(strValue);
- if (expires > 0)
- cookie.Expires = DateTime.Now.AddMinutes(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写Cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="key">键</param>
- /// <param name="strValue">值</param>
- /// <param name="expires">过期时间</param>
- public static void WriteCookie(string strName, string key, string strValue, int expires = 480)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie[key] = HttpContext.Current.Server.UrlEncode(strValue);
- //cookie.Domain = ".8200.cn";
- if (expires > 0)
- cookie.Expires = DateTime.Now.AddMinutes(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 读cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <returns>cookie值</returns>
- public static string GetCookie(string strName)
- {
- if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
- {
- //HttpContext.Current.Request.Cookies[strName].Domain = ".8200.cn";
- return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
- }
- return "";
- }
- /// <summary>
- /// 读cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="key">cookie键</param>
- /// <returns>cookie值</returns>
- public static string GetCookie(string strName, string key)
- {
- if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
- {
- //HttpContext.Current.Request.Cookies[strName].Domain = ".8200.cn";
- return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
- }
- return "";
- }
- /// <summary>
- /// 另外一个清理所有Cookie的方法
- /// </summary>
- public static void FlushAllCookie()
- {
- for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
- {
- HttpContext.Current.Response.Cookies[HttpContext.Current.Request.Cookies.Keys[i]].Expires = DateTime.Now.AddDays(-600);
- HttpContext.Current.Response.Cookies[HttpContext.Current.Request.Cookies.Keys[i]].Values.Clear();
- }
- }
- /// <summary>
- /// 移除Cookies
- /// </summary>
- /// <param name="cookiesName"></param>
- public static void RemoveCookies(string cookiesName)
- {
- if (string.IsNullOrEmpty(cookiesName))
- return;
- HttpCookie cookies = HttpContext.Current.Request.Cookies[cookiesName];
- if (null != cookies)
- {
- //HttpContext.Current.Response.Cookies[cookiesName].Domain = ".8200.cn";
- HttpContext.Current.Response.Cookies[cookiesName].Expires = DateTime.Now.AddDays(-600);
- HttpContext.Current.Response.Cookies[cookiesName].Values.Clear();
- }
- }
- /// <summary>
- /// 将IP地址转为整数形式
- /// </summary>
- /// <returns>整数</returns>
- public static long IP2Long(IPAddress ip)
- {
- int x = 3;
- long o = 0;
- foreach (byte f in ip.GetAddressBytes())
- {
- o += (long)f << 8 * x--;
- }
- return o;
- }
- /// <summary>
- /// 将整数转为IP地址
- /// </summary>
- /// <returns>IP地址</returns>
- public static IPAddress Long2IP(long l)
- {
- byte[] b = new byte[4];
- for (int i = 0; i < 4; i++)
- {
- b[3 - i] = (byte)(l >> 8 * i & 255);
- }
- return new IPAddress(b);
- }
- /// <summary>
- /// 生成随机因子
- /// </summary>
- /// <returns></returns>
- static int GetRandomSeed()
- {
- byte[] bytes = new byte[4];
- System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
- rng.GetBytes(bytes);
- return BitConverter.ToInt32(bytes, 0);
- }
- /// <summary>
- /// 生成min-max的随机数
- /// </summary>
- /// <param name="min"></param>
- /// <param name="max"></param>
- /// <returns></returns>
- public static int GetRandomInt(int min, int max)
- {
- Random random = new Random(GetRandomSeed());
- return random.Next(min, max);
- }
- /// <summary>
- /// 生成4位数字随机数
- /// </summary>
- /// <returns></returns>
- public static string GetRandomInt()
- {
- Random random = new Random();
- return (random.Next(1000, 9999).ToString());
- }
- /// <summary>
- /// 去除List中重复的项
- /// </summary>
- /// <param name="list"></param>
- /// <returns></returns>
- public static List<string> getUnque(List<string> list)
- {
- List<string> list1 = new List<string>();
- Hashtable hash = new Hashtable();
- foreach (string stu in list)
- {
- if (!hash.ContainsKey(stu))
- {
- hash.Add(stu, stu);
- list1.Add(stu);
- }
- }
- hash.Clear();
- hash = null;
- return list1;
- }
- /// <summary>
- /// 返回字符串真实长度, 1个汉字长度为2
- /// </summary>
- /// <returns>字符长度</returns>
- public static int GetStringLength(string str)
- {
- return Encoding.Default.GetBytes(str).Length;
- }
- /// <summary>
- /// 判断指定字符串在指定字符串数组中的位置
- /// </summary>
- /// <param name="strSearch">字符串</param>
- /// <param name="stringArray">字符串数组</param>
- /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
- /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
- public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
- {
- for (int i = 0; i < stringArray.Length; i++)
- {
- if (caseInsensetive)
- {
- if (strSearch.ToLower() == stringArray[i].ToLower())
- return i;
- }
- else if (strSearch == stringArray[i])
- return i;
- }
- return -1;
- }
- /// <summary>
- /// 判断指定字符串在指定字符串数组中的位置
- /// </summary>
- /// <param name="strSearch">字符串</param>
- /// <param name="stringArray">字符串数组</param>
- /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
- public static int GetInArrayID(string strSearch, string[] stringArray)
- {
- return GetInArrayID(strSearch, stringArray, true);
- }
- /// <summary>
- /// 判断指定字符串是否属于指定字符串数组中的一个元素
- /// </summary>
- /// <param name="strSearch">字符串</param>
- /// <param name="stringArray">字符串数组</param>
- /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
- /// <returns>判断结果</returns>
- public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
- {
- return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
- }
- /// <summary>
- /// 判断指定字符串是否属于指定字符串数组中的一个元素
- /// </summary>
- /// <param name="str">字符串</param>
- /// <param name="stringarray">字符串数组</param>
- /// <returns>判断结果</returns>
- public static bool InArray(string str, string[] stringarray)
- {
- return InArray(str, stringarray, false);
- }
- /// <summary>
- /// 判断指定字符串是否属于指定字符串数组中的一个元素
- /// </summary>
- /// <param name="str">字符串</param>
- /// <param name="stringarray">内部以逗号分割单词的字符串</param>
- /// <returns>判断结果</returns>
- public static bool InArray(string str, string stringarray)
- {
- return InArray(str, SplitString(stringarray, ","), false);
- }
- /// <summary>
- /// 判断指定字符串是否属于指定字符串数组中的一个元素
- /// </summary>
- /// <param name="str">字符串</param>
- /// <param name="stringarray">内部以逗号分割单词的字符串</param>
- /// <param name="strsplit">分割字符串</param>
- /// <returns>判断结果</returns>
- public static bool InArray(string str, string stringarray, string strsplit)
- {
- return InArray(str, SplitString(stringarray, strsplit), false);
- }
- /// <summary>
- /// 判断指定字符串是否属于指定字符串数组中的一个元素
- /// </summary>
- /// <param name="str">字符串</param>
- /// <param name="stringarray">内部以逗号分割单词的字符串</param>
- /// <param name="strsplit">分割字符串</param>
- /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
- /// <returns>判断结果</returns>
- public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive)
- {
- return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
- }
- public static string CutString(string str, int length)
- {
- return CutString(str, 0, length);
- }
- /// <summary>
- /// 从字符串的指定位置开始截取到字符串结尾的了符串
- /// </summary>
- /// <param name="str">原字符串</param>
- /// <param name="startIndex">子字符串的起始位置</param>
- /// <returns>子字符串</returns>
- private static string CutString(string str, int startIndex, int length)
- {
- if (startIndex >= 0)
- {
- if (length < 0)
- {
- length = length * -1;
- if (startIndex - length < 0)
- {
- length = startIndex;
- startIndex = 0;
- }
- else
- {
- startIndex = startIndex - length;
- }
- }
- if (startIndex > str.Length)
- {
- return "";
- }
- }
- else
- {
- if (length < 0)
- {
- return "";
- }
- else
- {
- if (length + startIndex > 0)
- {
- length = length + startIndex;
- startIndex = 0;
- }
- else
- {
- return "";
- }
- }
- }
- if (str.Length - startIndex < length)
- {
- length = str.Length - startIndex;
- }
- return str.Substring(startIndex, length);
- }
- /// <summary>
- /// 获得当前绝对路径
- /// </summary>
- /// <param name="strPath">指定的路径</param>
- /// <returns>绝对路径</returns>
- public static string GetMapPath(string strPath)
- {
- if (HttpContext.Current != null)
- {
- return HttpContext.Current.Server.MapPath(strPath);
- }
- else
- {
- strPath = strPath.Replace("/", "\\");
- if (strPath.StartsWith("\\"))
- {
- strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
- }
- return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
- }
- }
- /// <summary>
- /// 返回文件是否存在
- /// </summary>
- /// <param name="filename">文件名</param>
- /// <returns>是否存在</returns>
- public static bool FileExists(string filename)
- {
- return System.IO.File.Exists(filename);
- }
- /// <summary>
- /// 以指定的ContentType输出指定文件文件
- /// </summary>
- /// <param name="filepath">文件路径</param>
- /// <param name="filename">输出的文件名</param>
- /// <param name="filetype">将文件输出时设置的ContentType</param>
- public static void ResponseFile(string filepath, string filename, string filetype)
- {
- Stream iStream = null;
- // 缓冲区为10k
- byte[] buffer = new Byte[10000];
- // 文件长度
- int length;
- // 需要读的数据长度
- long dataToRead;
- try
- {
- // 打开文件
- iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
- // 需要读的数据长度
- dataToRead = iStream.Length;
- HttpContext.Current.Response.ContentType = filetype;
- if (HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].IndexOf("MSIE") > -1)
- HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(filename.Trim()).Replace("+", " "));
- else
- HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename.Trim());
- while (dataToRead > 0)
- {
- // 检查客户端是否还处于连接状态
- if (HttpContext.Current.Response.IsClientConnected)
- {
- length = iStream.Read(buffer, 0, 10000);
- HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
- HttpContext.Current.Response.Flush();
- buffer = new Byte[10000];
- dataToRead = dataToRead - length;
- }
- else
- {
- // 如果不再连接则跳出死循环
- dataToRead = -1;
- }
- }
- }
- catch (Exception ex)
- {
- HttpContext.Current.Response.Write("Error : " + ex.Message);
- }
- finally
- {
- if (iStream != null)
- {
- // 关闭文件
- iStream.Close();
- }
- }
- HttpContext.Current.Response.End();
- }
- /// <summary>
- /// int型转换为string型
- /// </summary>
- /// <returns>转换后的string类型结果</returns>
- public static string IntToStr(int intValue)
- {
- return Convert.ToString(intValue);
- }
- /// <summary>
- /// MD5函数
- /// 返回值为大写
- /// </summary>
- /// <param name="str">原始字符串</param>
- /// <returns>MD5结果</returns>
- public static string MD5(string str)
- {
- if (string.IsNullOrEmpty(str))
- return "";
- //加了码的md5
- str = "www." + str + ".8200.cn";
- byte[] b = Encoding.UTF8.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.ToUpper();
- }
- /// <summary>
- /// 通用MD5函数,未加码
- /// 返回值为大写
- /// </summary>
- /// <param name="str">原始字符串</param>
- /// <returns>MD5结果</returns>
- public static string GetMD5(string str)
- {
- if (string.IsNullOrEmpty(str))
- return "";
- byte[] b = Encoding.UTF8.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.ToUpper();
- }
- /// <summary>
- /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
- /// </summary>
- /// <param name="p_SrcString">要检查的字符串</param>
- /// <param name="p_Length">指定长度</param>
- /// <param name="p_TailString">用于替换的字符串</param>
- /// <returns>截取后的字符串</returns>
- public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
- {
- return GetSubString(p_SrcString, 0, p_Length, p_TailString);
- }
- public static string GetUnicodeSubString(string str, int len, string p_TailString)
- {
- string result = string.Empty;// 最终返回的结果
- int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
- int charLen = str.Length;// 把字符平等对待时的字符串长度
- int byteCount = 0;// 记录读取进度
- int pos = 0;// 记录截取位置
- if (byteLen > len)
- {
- for (int i = 0; i < charLen; i++)
- {
- if (TypeConverter.ObjectToInt(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
- byteCount += 2;
- else// 按英文字符计算加1
- byteCount += 1;
- if (byteCount > len)// 超出时只记下上一个有效位置
- {
- pos = i;
- break;
- }
- else if (byteCount == len)// 记下当前位置
- {
- pos = i + 1;
- break;
- }
- }
- if (pos >= 0)
- result = str.Substring(0, pos) + p_TailString;
- }
- else
- result = str;
- return result;
- }
- /// <summary>
- /// 取指定长度的字符串
- /// </summary>
- /// <param name="p_SrcString">要检查的字符串</param>
- /// <param name="p_StartIndex">起始位置</param>
- /// <param name="p_Length">指定长度</param>
- /// <param name="p_TailString">用于替换的字符串</param>
- /// <returns>截取后的字符串</returns>
- public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
- {
- string myResult = p_SrcString;
- Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString);
- foreach (char c in Encoding.UTF8.GetChars(bComments))
- { //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
- if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3'))
- {
- //if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
- //当截取的起始位置超出字段串长度时
- if (p_StartIndex >= p_SrcString.Length)
- return "";
- else
- return p_SrcString.Substring(p_StartIndex,
- ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
- }
- }
- if (p_Length >= 0)
- {
- byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
- //当字符串长度大于起始位置
- if (bsSrcString.Length > p_StartIndex)
- {
- int p_EndIndex = bsSrcString.Length;
- //当要截取的长度在字符串的有效长度范围内
- if (bsSrcString.Length > (p_StartIndex + p_Length))
- {
- p_EndIndex = p_Length + p_StartIndex;
- }
- else
- { //当不在有效范围内时,只取到字符串的结尾
- p_Length = bsSrcString.Length - p_StartIndex;
- p_TailString = "";
- }
- int nRealLength = p_Length;
- int[] anResultFlag = new int[p_Length];
- byte[] bsResult = null;
- int nFlag = 0;
- for (int i = p_StartIndex; i < p_EndIndex; i++)
- {
- if (bsSrcString[i] > 127)
- {
- nFlag++;
- if (nFlag == 3)
- nFlag = 1;
- }
- else
- nFlag = 0;
- anResultFlag[i] = nFlag;
- }
- if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
- nRealLength = p_Length + 1;
- bsResult = new byte[nRealLength];
- Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);
- myResult = Encoding.Default.GetString(bsResult);
- myResult = myResult + p_TailString;
- }
- }
- return myResult;
- }
- /// <summary>
- /// 自定义的替换字符串函数
- /// </summary>
- 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);
- }
- /// <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\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
- }
- /// <summary>
- /// 检测是否有Sql危险字符
- /// </summary>
- /// <param name="str">要判断字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsSafeSqlString(string str)
- {
- return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
- }
- /// <summary>
- /// 检测是否有危险的可能用于链接的字符串
- /// </summary>
- /// <param name="str">要判断字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsSafeUserInfoString(string str)
- {
- return !Regex.IsMatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest|管理员|彩站|彩宝|8200");
- }
- /// <summary>
- /// 清理字符串
- /// </summary>
- public static string CleanInput(string strIn)
- {
- return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
- }
- /// <summary>
- /// 返回URL中结尾的文件名
- /// </summary>
- public static string GetFilename(string url)
- {
- if (url == null)
- {
- return "";
- }
- string[] strs1 = url.Split(new char[] { '/' });
- return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
- }
- /// <summary>
- /// 判断字符串是否为时间
- /// </summary>
- /// <returns></returns>
- public static bool IsTime(string timeval)
- {
- return Regex.IsMatch(timeval, @"^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$");
- }
- /// <summary>
- /// 改正sql语句中的转义字符
- /// </summary>
- public static string mashSQL(string str)
- {
- return (str == null) ? "" : str.Replace("\'", "'");
- }
- /// <summary>
- /// 替换sql语句中的有问题符号
- /// </summary>
- public static string ChkSQL(string str)
- {
- return (str == null) ? "" : str.Replace("'", "''");
- }
- /// <summary>
- /// 转换为静态html
- /// </summary>
- public void transHtml(string path, string outpath)
- {
- Page page = new Page();
- StringWriter writer = new StringWriter();
- page.Server.Execute(path, writer);
- FileStream fs;
- if (File.Exists(page.Server.MapPath("") + "\\" + outpath))
- {
- File.Delete(page.Server.MapPath("") + "\\" + outpath);
- fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
- }
- else
- {
- fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
- }
- byte[] bt = Encoding.Default.GetBytes(writer.ToString());
- fs.Write(bt, 0, bt.Length);
- fs.Close();
- }
- /// <summary>
- /// 分割字符串
- /// </summary>
- public static string[] SplitString(string strContent, string strSplit)
- {
- if (!String.IsNullOrEmpty(strContent))
- {
- if (strContent.IndexOf(strSplit) < 0)
- return new string[] { strContent };
- return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
- }
- else
- return new string[0] { };
- }
- /// <summary>
- /// 分割字符串
- /// </summary>
- /// <returns></returns>
- public static string[] SplitString(string strContent, string strSplit, int count)
- {
- string[] result = new string[count];
- string[] splited = SplitString(strContent, strSplit);
- for (int i = 0; i < count; i++)
- {
- if (i < splited.Length)
- result[i] = splited[i];
- else
- result[i] = string.Empty;
- }
- return result;
- }
- /// <summary>
- /// 过滤字符串数组中每个元素为合适的大小
- /// 当长度小于minLength时,忽略掉,-1为不限制最小长度
- /// 当长度大于maxLength时,取其前maxLength位
- /// 如果数组中有null元素,会被忽略掉
- /// </summary>
- /// <param name="minLength">单个元素最小长度</param>
- /// <param name="maxLength">单个元素最大长度</param>
- /// <returns></returns>
- public static string[] PadStringArray(string[] strArray, int minLength, int maxLength)
- {
- if (minLength > maxLength)
- {
- int t = maxLength;
- maxLength = minLength;
- minLength = t;
- }
- int iMiniStringCount = 0;
- for (int i = 0; i < strArray.Length; i++)
- {
- if (minLength > -1 && strArray[i].Length < minLength)
- {
- strArray[i] = null;
- continue;
- }
- if (strArray[i].Length > maxLength)
- strArray[i] = strArray[i].Substring(0, maxLength);
- iMiniStringCount++;
- }
- string[] result = new string[iMiniStringCount];
- for (int i = 0, j = 0; i < strArray.Length && j < result.Length; i++)
- {
- if (strArray[i] != null && strArray[i] != string.Empty)
- {
- result[j] = strArray[i];
- j++;
- }
- }
- return result;
- }
- /// <summary>
- /// 分割字符串
- /// </summary>
- /// <param name="strContent">被分割的字符串</param>
- /// <param name="strSplit">分割符</param>
- /// <param name="ignoreRepeatItem">忽略重复项</param>
- /// <param name="maxElementLength">单个元素最大长度</param>
- /// <returns></returns>
- public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int maxElementLength)
- {
- string[] result = SplitString(strContent, strSplit);
- return ignoreRepeatItem ? DistinctStringArray(result, maxElementLength) : result;
- }
- public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int minElementLength, int maxElementLength)
- {
- string[] result = SplitString(strContent, strSplit);
- if (ignoreRepeatItem)
- {
- result = DistinctStringArray(result);
- }
- return PadStringArray(result, minElementLength, maxElementLength);
- }
- /// <summary>
- /// 分割字符串
- /// </summary>
- /// <param name="strContent">被分割的字符串</param>
- /// <param name="strSplit">分割符</param>
- /// <param name="ignoreRepeatItem">忽略重复项</param>
- /// <returns></returns>
- public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem)
- {
- return SplitString(strContent, strSplit, ignoreRepeatItem, 0);
- }
- /// <summary>
- /// 清除字符串数组中的重复项
- /// </summary>
- /// <param name="strArray">字符串数组</param>
- /// <param name="maxElementLength">字符串数组中单个元素的最大长度</param>
- /// <returns></returns>
- public static string[] DistinctStringArray(string[] strArray, int maxElementLength)
- {
- Hashtable h = new Hashtable();
- foreach (string s in strArray)
- {
- string k = s;
- if (maxElementLength > 0 && k.Length > maxElementLength)
- {
- k = k.Substring(0, maxElementLength);
- }
- h[k.Trim()] = s;
- }
- string[] result = new string[h.Count];
- h.Keys.CopyTo(result, 0);
- return result;
- }
- /// <summary>
- /// 清除字符串数组中的重复项
- /// </summary>
- /// <param name="strArray">字符串数组</param>
- /// <returns></returns>
- public static string[] DistinctStringArray(string[] strArray)
- {
- return DistinctStringArray(strArray, 0);
- }
- /// <summary>
- /// 替换html字符
- /// </summary>
- public static string EncodeHtml(string strHtml)
- {
- if (strHtml != "")
- {
- strHtml = strHtml.Replace(",", "&def");
- strHtml = strHtml.Replace("'", "&dot");
- strHtml = strHtml.Replace(";", "&dec");
- return strHtml;
- }
- return "";
- }
- /// <summary>
- /// 进行指定的替换(脏字过滤)
- /// </summary>
- public static string StrFilter(string str, string bantext)
- {
- string text1 = "", text2 = "";
- string[] textArray1 = SplitString(bantext, "\r\n");
- for (int num1 = 0; num1 < textArray1.Length; num1++)
- {
- text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
- text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1);
- str = str.Replace(text1, text2);
- }
- return str;
- }
- /// <summary>
- /// 返回 HTML 字符串的编码结果
- /// </summary>
- /// <param name="str">字符串</param>
- /// <returns>编码结果</returns>
- public static string HtmlEncode(string str)
- {
- return HttpUtility.HtmlEncode(str);
- }
- /// <summary>
- /// 返回 HTML 字符串的解码结果
- /// </summary>
- /// <param name="str">字符串</param>
- /// <returns>解码结果</returns>
- public static string HtmlDecode(string str)
- {
- return HttpUtility.HtmlDecode(str);
- }
- /// <summary>
- /// 返回 URL 字符串的编码结果
- /// </summary>
- /// <param name="str">字符串</param>
- /// <returns>编码结果</returns>
- public static string UrlEncode(string str)
- {
- return HttpUtility.UrlEncode(str);
- }
- /// <summary>
- /// 返回 URL 字符串的编码结果
- /// </summary>
- /// <param name="str">字符串</param>
- /// <returns>解码结果</returns>
- public static string UrlDecode(string str)
- {
- return HttpUtility.UrlDecode(str);
- }
- /// <summary>
- /// 返回指定目录下的非 UTF8 字符集文件
- /// </summary>
- /// <param name="Path">路径</param>
- /// <returns>文件名的字符串数组</returns>
- public static string[] FindNoUTF8File(string Path)
- {
- StringBuilder filelist = new StringBuilder();
- DirectoryInfo Folder = new DirectoryInfo(Path);
- FileInfo[] subFiles = Folder.GetFiles();
- for (int j = 0; j < subFiles.Length; j++)
- {
- if (subFiles[j].Extension.ToLower().Equals(".htm"))
- {
- FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
- bool bUtf8 = IsUTF8(fs);
- fs.Close();
- if (!bUtf8)
- {
- filelist.Append(subFiles[j].FullName);
- filelist.Append("\r\n");
- }
- }
- }
- return Utils.SplitString(filelist.ToString(), "\r\n");
- }
- //0000 0000-0000 007F - 0xxxxxxx (ascii converts to 1 octet!)
- //0000 0080-0000 07FF - 110xxxxx 10xxxxxx ( 2 octet format)
- //0000 0800-0000 FFFF - 1110xxxx 10xxxxxx 10xxxxxx (3 octet format)
- /// <summary>
- /// 判断文件流是否为UTF8字符集
- /// </summary>
- /// <param name="sbInputStream">文件流</param>
- /// <returns>判断结果</returns>
- private static bool IsUTF8(FileStream sbInputStream)
- {
- int i;
- byte cOctets; // octets to go in this UTF-8 encoded character
- byte chr;
- bool bAllAscii = true;
- long iLen = sbInputStream.Length;
- cOctets = 0;
- for (i = 0; i < iLen; i++)
- {
- chr = (byte)sbInputStream.ReadByte();
- if ((chr & 0x80) != 0) bAllAscii = false;
- if (cOctets == 0)
- {
- if (chr >= 0x80)
- {
- do
- {
- chr <<= 1;
- cOctets++;
- }
- while ((chr & 0x80) != 0);
- cOctets--;
- if (cOctets == 0)
- return false;
- }
- }
- else
- {
- if ((chr & 0xC0) != 0x80)
- return false;
- cOctets--;
- }
- }
- if (cOctets > 0)
- return false;
- if (bAllAscii)
- return false;
- return true;
- }
- /// <summary>
- /// 是否为ip
- /// </summary>
- /// <param name="ip"></param>
- /// <returns></returns>
- public static bool IsIP(string ip)
- {
- return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
- }
- public static bool IsIPSect(string ip)
- {
- return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
- }
- /// <summary>
- /// 将全角数字转换为数字
- /// </summary>
- /// <param name="SBCCase"></param>
- /// <returns></returns>
- public static string SBCCaseToNumberic(string SBCCase)
- {
- char[] c = SBCCase.ToCharArray();
- for (int i = 0; i < c.Length; i++)
- {
- byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
- if (b.Length == 2)
- {
- if (b[1] == 255)
- {
- b[0] = (byte)(b[0] + 32);
- b[1] = 0;
- c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
- }
- }
- }
- return new string(c);
- }
- /// <summary>
- /// 移除Html标记
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- public static string RemoveHtml(string content)
- {
- return Regex.Replace(content, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
- }
- /// <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>
- /// object型转换为bool型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的bool类型结果</returns>
- public static bool StrToBool(object expression, bool defValue)
- {
- return TypeConverter.StrToBool(expression, defValue);
- }
- /// <summary>
- /// string型转换为bool型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的bool类型结果</returns>
- public static bool StrToBool(string expression, bool defValue)
- {
- return TypeConverter.StrToBool(expression, defValue);
- }
- /// <summary>
- /// 将对象转换为Int32类型
- /// </summary>
- /// <param name="expression">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static int StrToInt(object expression, int defValue)
- {
- return TypeConverter.ObjectToInt(expression, defValue);
- }
- /// <summary>
- /// 将字符串转换为Int32类型
- /// </summary>
- /// <param name="expression">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static int StrToInt(string expression, int defValue)
- {
- return TypeConverter.StrToInt(expression, defValue);
- }
- /// <summary>
- /// Object型转换为float型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static float StrToFloat(object strValue, float defValue)
- {
- return TypeConverter.StrToFloat(strValue, defValue);
- }
- /// <summary>
- /// string型转换为float型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static float StrToFloat(string strValue, float defValue)
- {
- return TypeConverter.StrToFloat(strValue, defValue);
- }
- /// <summary>
- /// 验证是否为正整数
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static bool IsInt(string str)
- {
- return Regex.IsMatch(str, @"^[0-9]*$");
- }
- /// <summary>
- /// 根据Url获得源文件内容
- /// </summary>
- /// <param name="url">合法的Url地址</param>
- /// <returns></returns>
- public static string GetSourceTextByUrl(string url)
- {
- try
- {
- WebRequest request = WebRequest.Create(url);
- request.Timeout = 20000;//20秒超时
- WebResponse response = request.GetResponse();
- Stream resStream = response.GetResponseStream();
- StreamReader sr = new StreamReader(resStream);
- return sr.ReadToEnd();
- }
- catch { return ""; }
- }
- /// <summary>
- /// 合并字符
- /// </summary>
- /// <param name="source">要合并的源字符串</param>
- /// <param name="target">要被合并到的目的字符串</param>
- /// <param name="mergechar">合并符</param>
- /// <returns>合并到的目的字符串</returns>
- public static string MergeString(string source, string target)
- {
- return MergeString(source, target, ",");
- }
- /// <summary>
- /// 合并字符
- /// </summary>
- /// <param name="source">要合并的源字符串</param>
- /// <param name="target">要被合并到的目的字符串</param>
- /// <param name="mergechar">合并符</param>
- /// <returns>并到字符串</returns>
- public static string MergeString(string source, string target, string mergechar)
- {
- if (String.IsNullOrEmpty(target))
- target = source;
- else
- target += mergechar + source;
- return target;
- }
- /// <summary>
- /// 清除UBB标签
- /// </summary>
- /// <param name="sDetail">帖子内容</param>
- /// <returns>帖子内容</returns>
- public static string ClearUBB(string sDetail)
- {
- return Regex.Replace(sDetail, @"\[[^\]]*?\]", string.Empty, RegexOptions.IgnoreCase);
- }
- /// <summary>
- /// 获取站点根目录URL
- /// </summary>
- /// <returns></returns>
- public static string GetRootUrl(string forumPath)
- {
- int port = HttpContext.Current.Request.Url.Port;
- return string.Format("{0}://{1}{2}{3}",
- HttpContext.Current.Request.Url.Scheme,
- HttpContext.Current.Request.Url.Host.ToString(),
- (port == 80 || port == 0) ? "" : ":" + port,
- forumPath);
- }
- /// <summary>
- /// 获取指定文件的扩展名
- /// </summary>
- /// <param name="fileName">指定文件名</param>
- /// <returns>扩展名</returns>
- public static string GetFileExtName(string fileName)
- {
- if (String.IsNullOrEmpty(fileName) || fileName.IndexOf('.') <= 0)
- return "";
- fileName = fileName.ToLower().Trim();
- return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
- }
- /// <summary>
- /// http POST请求url
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string GetHttpWebResponse(string url)
- {
- return GetHttpWebResponse(url, string.Empty);
- }
- /// <summary>
- /// http POST请求url
- /// </summary>
- /// <param name="apiUrl"></param>
- /// <param name="method_name"></param>
- /// <param name="postData"></param>
- /// <returns></returns>
- public static string GetHttpWebResponse(string url, string postData)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = postData.Length;
- request.Timeout = 20000;
- HttpWebResponse response = null;
- try
- {
- StreamWriter swRequestWriter = new StreamWriter(request.GetRequestStream());
- swRequestWriter.Write(postData);
- if (swRequestWriter != null)
- swRequestWriter.Close();
- response = (HttpWebResponse)request.GetResponse();
- using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
- {
- return reader.ReadToEnd();
- }
- }
- finally
- {
- if (response != null)
- response.Close();
- }
- }
- #region Private Methods
- private static string[] browerNames = { "MSIE", "Firefox", "Opera", "Netscape", "Safari", "Lynx", "Konqueror", "Mozilla" };
- //private const string[] osNames = { "Win", "Mac", "Linux", "FreeBSD", "SunOS", "OS/2", "AIX", "Bot", "Crawl", "Spider" };
- /// <summary>
- /// 获得浏览器信息
- /// </summary>
- /// <returns></returns>
- public static string GetClientBrower()
- {
- string agent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
- if (!string.IsNullOrEmpty(agent))
- {
- foreach (string name in browerNames)
- {
- if (agent.Contains(name))
- return name;
- }
- }
- return "Other";
- }
- /// <summary>
- /// 获得操作系统信息
- /// </summary>
- /// <returns></returns>
- public static string GetClientOS()
- {
- string os = string.Empty;
- string agent = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
- if (agent == null)
- return "Other";
- if (agent.IndexOf("Win") > -1)
- os = "Windows";
- else if (agent.IndexOf("Mac") > -1)
- os = "Mac";
- else if (agent.IndexOf("Linux") > -1)
- os = "Linux";
- else if (agent.IndexOf("FreeBSD") > -1)
- os = "FreeBSD";
- else if (agent.IndexOf("SunOS") > -1)
- os = "SunOS";
- else if (agent.IndexOf("OS/2") > -1)
- os = "OS/2";
- else if (agent.IndexOf("AIX") > -1)
- os = "AIX";
- else if (System.Text.RegularExpressions.Regex.IsMatch(agent, @"(Bot|Crawl|Spider)"))
- os = "Spiders";
- else
- os = "Other";
- return os;
- }
- #endregion
- }
- }
|