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
{
///
/// 工具类
///
public class Utils
{
#region 获取Int星期值
///
/// 获取int星期值
///
///
///
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
///
/// 验证是否为整数,且大于min
///
///
///
///
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;
}
///
/// 下期奖池、投注金额
///
///
///
///
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;
}
///
/// 分析开奖号,组六0、组三2、豹子3
///
///
///
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;
}
///
/// 邮件发送程序
///
///
///
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;
}
///
/// 生成永不重复的字串..
/// 然后md5
///
///
public static string GetRandomString()
{
string key = System.Guid.NewGuid().ToString().Replace("-", "");
return MD5(key);
}
///
/// 返回url的根域名
///
///
///
public static string GetUrlDomainName(string url)
{
string p = @"^https?://(?[^/]+)(/|$)";
Regex reg = new Regex(p, RegexOptions.IgnoreCase);
Match m = reg.Match(url);
return m.Groups["domain"].Value.ToString().Trim();
}
///
/// 取图片源地址string[]
///
///
///
public static string[] GetHtmlImageUrlList(string content)
{
// 定义正则表达式用来匹配 img 标签
Regex regImg = new Regex(@"
]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?[^\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;
}
///
/// http post
///
///
///
///
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;
}
///
/// HTTP Get请求
///
/// 地址
///
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;
}
///
/// 下载网络图片
/// 返回二进制流
///
///
///
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;
}
///
/// 根据字符长度,返回n个*号
///
///
///
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();
}
///
/// 截取固定长度并不带html字串的方法
///
///
///
///
public static string GetCutNoHtmlString(string str, int len)
{
str = RemoveHtml(str);
str = str.Replace("
", "");
str = str.Replace("
", "");
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) + "...";
}
///
/// 算出数组中出现次数最多的 元素+次数
/// 返回 7-3 格式
///
///
///
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 + "(" + maxValue + ")";
}
///
/// 构造出3d/p3的1000注所有号码
///
///
public static List GetAllNumber()
{
List list = new List();
for (int i = 0; i < 1000; i++)
list.Add(i);
return list;
}
///
/// 取站点的http://+domain部分..
///
///
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;
}
///
/// 读取某相对路径下的文本文件内容
///
/// 相对路径
///
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;
}
///
/// 获得当前页面客户端的IP
///
/// 当前页面客户端的IP
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;
}
///
/// 写Cookie值
///
/// 键
/// 名
/// httponly默认true
/// 默认480分钟
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);
}
///
/// 写Cookie值
///
/// 名称
/// 键
/// 值
/// 过期时间
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);
}
///
/// 读cookie值
///
/// 名称
/// cookie值
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 "";
}
///
/// 读cookie值
///
/// 名称
/// cookie键
/// cookie值
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 "";
}
///
/// 另外一个清理所有Cookie的方法
///
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();
}
}
///
/// 移除Cookies
///
///
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();
}
}
///
/// 将IP地址转为整数形式
///
/// 整数
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;
}
///
/// 将整数转为IP地址
///
/// IP地址
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);
}
///
/// 生成随机因子
///
///
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);
}
///
/// 生成min-max的随机数
///
///
///
///
public static int GetRandomInt(int min, int max)
{
Random random = new Random(GetRandomSeed());
return random.Next(min, max);
}
///
/// 生成4位数字随机数
///
///
public static string GetRandomInt()
{
Random random = new Random();
return (random.Next(1000, 9999).ToString());
}
///
/// 去除List中重复的项
///
///
///
public static List getUnque(List list)
{
List list1 = new List();
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;
}
///
/// 返回字符串真实长度, 1个汉字长度为2
///
/// 字符长度
public static int GetStringLength(string str)
{
return Encoding.Default.GetBytes(str).Length;
}
///
/// 判断指定字符串在指定字符串数组中的位置
///
/// 字符串
/// 字符串数组
/// 是否不区分大小写, true为不区分, false为区分
/// 字符串在指定字符串数组中的位置, 如不存在则返回-1
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;
}
///
/// 判断指定字符串在指定字符串数组中的位置
///
/// 字符串
/// 字符串数组
/// 字符串在指定字符串数组中的位置, 如不存在则返回-1
public static int GetInArrayID(string strSearch, string[] stringArray)
{
return GetInArrayID(strSearch, stringArray, true);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 字符串数组
/// 是否不区分大小写, true为不区分, false为区分
/// 判断结果
public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
{
return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 字符串数组
/// 判断结果
public static bool InArray(string str, string[] stringarray)
{
return InArray(str, stringarray, false);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 内部以逗号分割单词的字符串
/// 判断结果
public static bool InArray(string str, string stringarray)
{
return InArray(str, SplitString(stringarray, ","), false);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 内部以逗号分割单词的字符串
/// 分割字符串
/// 判断结果
public static bool InArray(string str, string stringarray, string strsplit)
{
return InArray(str, SplitString(stringarray, strsplit), false);
}
///
/// 判断指定字符串是否属于指定字符串数组中的一个元素
///
/// 字符串
/// 内部以逗号分割单词的字符串
/// 分割字符串
/// 是否不区分大小写, true为不区分, false为区分
/// 判断结果
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);
}
///
/// 从字符串的指定位置开始截取到字符串结尾的了符串
///
/// 原字符串
/// 子字符串的起始位置
/// 子字符串
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);
}
///
/// 获得当前绝对路径
///
/// 指定的路径
/// 绝对路径
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);
}
}
///
/// 返回文件是否存在
///
/// 文件名
/// 是否存在
public static bool FileExists(string filename)
{
return System.IO.File.Exists(filename);
}
///
/// 以指定的ContentType输出指定文件文件
///
/// 文件路径
/// 输出的文件名
/// 将文件输出时设置的ContentType
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();
}
///
/// int型转换为string型
///
/// 转换后的string类型结果
public static string IntToStr(int intValue)
{
return Convert.ToString(intValue);
}
///
/// MD5函数
/// 返回值为大写
///
/// 原始字符串
/// MD5结果
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();
}
///
/// 通用MD5函数,未加码
/// 返回值为大写
///
/// 原始字符串
/// MD5结果
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();
}
///
/// 字符串如果操过指定长度则将超出的部分用指定字符串代替
///
/// 要检查的字符串
/// 指定长度
/// 用于替换的字符串
/// 截取后的字符串
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;
}
///
/// 取指定长度的字符串
///
/// 要检查的字符串
/// 起始位置
/// 指定长度
/// 用于替换的字符串
/// 截取后的字符串
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;
}
///
/// 自定义的替换字符串函数
///
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);
}
///
/// 检测是否是正确的Url
///
/// 要验证的Url
/// 判断结果
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\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
}
///
/// 检测是否有Sql危险字符
///
/// 要判断字符串
/// 判断结果
public static bool IsSafeSqlString(string str)
{
return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
}
///
/// 检测是否有危险的可能用于链接的字符串
///
/// 要判断字符串
/// 判断结果
public static bool IsSafeUserInfoString(string str)
{
return !Regex.IsMatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest|管理员|彩站|彩宝|8200");
}
///
/// 清理字符串
///
public static string CleanInput(string strIn)
{
return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
}
///
/// 返回URL中结尾的文件名
///
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];
}
///
/// 判断字符串是否为时间
///
///
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])?)$");
}
///
/// 改正sql语句中的转义字符
///
public static string mashSQL(string str)
{
return (str == null) ? "" : str.Replace("\'", "'");
}
///
/// 替换sql语句中的有问题符号
///
public static string ChkSQL(string str)
{
return (str == null) ? "" : str.Replace("'", "''");
}
///
/// 转换为静态html
///
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();
}
///
/// 分割字符串
///
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] { };
}
///
/// 分割字符串
///
///
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;
}
///
/// 过滤字符串数组中每个元素为合适的大小
/// 当长度小于minLength时,忽略掉,-1为不限制最小长度
/// 当长度大于maxLength时,取其前maxLength位
/// 如果数组中有null元素,会被忽略掉
///
/// 单个元素最小长度
/// 单个元素最大长度
///
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;
}
///
/// 分割字符串
///
/// 被分割的字符串
/// 分割符
/// 忽略重复项
/// 单个元素最大长度
///
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);
}
///
/// 分割字符串
///
/// 被分割的字符串
/// 分割符
/// 忽略重复项
///
public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem)
{
return SplitString(strContent, strSplit, ignoreRepeatItem, 0);
}
///
/// 清除字符串数组中的重复项
///
/// 字符串数组
/// 字符串数组中单个元素的最大长度
///
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;
}
///
/// 清除字符串数组中的重复项
///
/// 字符串数组
///
public static string[] DistinctStringArray(string[] strArray)
{
return DistinctStringArray(strArray, 0);
}
///
/// 替换html字符
///
public static string EncodeHtml(string strHtml)
{
if (strHtml != "")
{
strHtml = strHtml.Replace(",", "&def");
strHtml = strHtml.Replace("'", "&dot");
strHtml = strHtml.Replace(";", "&dec");
return strHtml;
}
return "";
}
///
/// 进行指定的替换(脏字过滤)
///
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;
}
///
/// 返回 HTML 字符串的编码结果
///
/// 字符串
/// 编码结果
public static string HtmlEncode(string str)
{
return HttpUtility.HtmlEncode(str);
}
///
/// 返回 HTML 字符串的解码结果
///
/// 字符串
/// 解码结果
public static string HtmlDecode(string str)
{
return HttpUtility.HtmlDecode(str);
}
///
/// 返回 URL 字符串的编码结果
///
/// 字符串
/// 编码结果
public static string UrlEncode(string str)
{
return HttpUtility.UrlEncode(str);
}
///
/// 返回 URL 字符串的编码结果
///
/// 字符串
/// 解码结果
public static string UrlDecode(string str)
{
return HttpUtility.UrlDecode(str);
}
///
/// 返回指定目录下的非 UTF8 字符集文件
///
/// 路径
/// 文件名的字符串数组
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)
///
/// 判断文件流是否为UTF8字符集
///
/// 文件流
/// 判断结果
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;
}
///
/// 是否为ip
///
///
///
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?|\*)$");
}
///
/// 将全角数字转换为数字
///
///
///
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);
}
///
/// 移除Html标记
///
///
///
public static string RemoveHtml(string content)
{
return Regex.Replace(content, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
}
///
/// 过滤HTML中的不安全标签
///
///
///
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;
}
///
/// object型转换为bool型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的bool类型结果
public static bool StrToBool(object expression, bool defValue)
{
return TypeConverter.StrToBool(expression, defValue);
}
///
/// string型转换为bool型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的bool类型结果
public static bool StrToBool(string expression, bool defValue)
{
return TypeConverter.StrToBool(expression, defValue);
}
///
/// 将对象转换为Int32类型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static int StrToInt(object expression, int defValue)
{
return TypeConverter.ObjectToInt(expression, defValue);
}
///
/// 将字符串转换为Int32类型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static int StrToInt(string expression, int defValue)
{
return TypeConverter.StrToInt(expression, defValue);
}
///
/// Object型转换为float型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float StrToFloat(object strValue, float defValue)
{
return TypeConverter.StrToFloat(strValue, defValue);
}
///
/// string型转换为float型
///
/// 要转换的字符串
/// 缺省值
/// 转换后的int类型结果
public static float StrToFloat(string strValue, float defValue)
{
return TypeConverter.StrToFloat(strValue, defValue);
}
///
/// 验证是否为正整数
///
///
///
public static bool IsInt(string str)
{
return Regex.IsMatch(str, @"^[0-9]*$");
}
///
/// 根据Url获得源文件内容
///
/// 合法的Url地址
///
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 ""; }
}
///
/// 合并字符
///
/// 要合并的源字符串
/// 要被合并到的目的字符串
/// 合并符
/// 合并到的目的字符串
public static string MergeString(string source, string target)
{
return MergeString(source, target, ",");
}
///
/// 合并字符
///
/// 要合并的源字符串
/// 要被合并到的目的字符串
/// 合并符
/// 并到字符串
public static string MergeString(string source, string target, string mergechar)
{
if (String.IsNullOrEmpty(target))
target = source;
else
target += mergechar + source;
return target;
}
///
/// 清除UBB标签
///
/// 帖子内容
/// 帖子内容
public static string ClearUBB(string sDetail)
{
return Regex.Replace(sDetail, @"\[[^\]]*?\]", string.Empty, RegexOptions.IgnoreCase);
}
///
/// 获取站点根目录URL
///
///
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);
}
///
/// 获取指定文件的扩展名
///
/// 指定文件名
/// 扩展名
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('.'));
}
///
/// http POST请求url
///
///
///
public static string GetHttpWebResponse(string url)
{
return GetHttpWebResponse(url, string.Empty);
}
///
/// http POST请求url
///
///
///
///
///
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" };
///
/// 获得浏览器信息
///
///
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";
}
///
/// 获得操作系统信息
///
///
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
}
}