/// <summary>
/// 服务器端产生客户端脚本的封装类
/// </summary>
public class jsHint
{
public jsHint()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 弹出提示信息
/// </summary>
/// <param name="parm">对话框里面的提示信息</param>
public static void Alert(string parm) //alert
{
HttpResponse response = HttpContext.Current.Response;
response.Write(string.Format("<script language=\"javascript\">alert('{0}');</script>", parm));
return;
}
/// <summary>
/// 提示信息并关闭当前(弹出)窗口
/// </summary>
/// <param name="parm">对话框里面的提示信息</param>
/// <param name="_close">1 表示关闭, 0 表示不关闭</param>
public static void Alert(string parm, int _close)
{
HttpResponse response = HttpContext.Current.Response;
if (_close == 1)
response.Write(string.Format("<script language=\"javascript\">alert('{0}');window.close();</script>", parm));
else
response.Write(string.Format("<script language=\"javascript\">alert('{0}');</script>", parm));
return;
}
public static void Alert(string parm, string script)
{
HttpResponse response = HttpContext.Current.Response;
response.Write(string.Format("<script language=\"javascript\">alert('{0}');{1}</script>", parm, script));
return;
}
/// <summary>
/// 显示提示信息并刷新父窗口内容,一般用在弹出窗口上需要提示用户的地方
/// </summary>
/// <param name="parm">对话框里面的提示信息</param>
/// <param name="_close">1 表示关闭当前窗口, 0 表示不关闭当前窗口</param>
/// <param name="_refparent">1 表示刷新父窗口, 0 表示不刷新</param>
public static void Alert(string parm, int _close, int _refparent)
{
HttpResponse response = HttpContext.Current.Response;
if (_close == 1 && _refparent == 1)
response.Write(string.Format("<script language=\"javascript\">alert('{0}');self.close();opener.location.reload();</script>", parm));
else
response.Write(string.Format("<script language=\"javascript\">alert('{0}');</script>", parm));
return;
}
/// <summary>
/// 显示信息并刷新父窗口
/// </summary>
/// <param name="parm"></param>
/// <param name="_refparent"></param>
public static void Alert(string parm, bool _refparent)
{
HttpResponse response = HttpContext.Current.Response;
if (_refparent)
response.Write(string.Format("<script language=\"javascript\">alert('{0}');parent.parent.location.reload();</script>", parm));
else
response.Write(string.Format("<script language=\"javascript\">alert('{0}');</script>", parm));
return;
}
/// <summary>
/// 显示提示信息并将父窗口重定向到 parentUrl
/// </summary>
/// <param name="parm">对话框里面的提示信息</param>
/// <param name="_close">1 表示关闭当前窗口, 0 表示不关闭当前窗口</param>
/// <param name="parentUrl">要将父窗口定向到的地址</param>
public static void Alert(string parm, int _close, string parentUrl)
{
HttpResponse response = HttpContext.Current.Response;
if (_close == 1)
response.Write(string.Format("<script language=\"javascript\">alert('{0}');window.close();opener.location.href='{1}';</script>", parm, parentUrl));
else
response.Write(string.Format("<script language=\"javascript\">alert('{0}');</script>", parm));
return;
}
// /// <summary>
// /// 显示提示信息并将当前窗口重定向到 toUrl
// /// </summary>
// /// <param name="parm">对话框里面的提示信息</param>
// /// <param name="toUrl">要将当前窗口定向到的地址</param>
// public static void Alert(string parm,string toUrl)
// {
// HttpResponse response = HttpContext.Current.Response;
// response.Write(string.Format("<script language=\"javascript\">alert('{0}');window.location.href='{1}';</script>",parm,toUrl));
//
// return;
// }
// /// <summary>
// ///
// /// </summary>
// /// <param name="parm"></param>
// /// <param name="refparent"></param>
// public static void Alert(string parm,bool refparent)
// {
// HttpResponse response = HttpContext.Current.Response;
// response.Write(string.Format("<script language=\"javascript\">alert('{0}');parent.parent.reload();</script>",parm,toUrl));
//
// return;
// }
/// <summary>
/// 显示询问对话框
/// </summary>
/// <param name="qstr">要询问操作者的内容</param>
public static void Confirm(string qstr)
{
HttpResponse response = HttpContext.Current.Response;
response.Write(string.Format("<script language=\"javascript\">confirm('{0}');</script>", qstr));
return;
}
/// <summary>
/// 显示询问对话框并根据用户的选择将当前窗口重定向到相应的地址
/// </summary>
/// <param name="qstr">要询问操作者的内容</param>
/// <param name="toUrl">如果用户肯定询问内容则将当前窗口重定向到此地址</param>
/// <param name="backUrl">如果用户否定询问内容则将当前窗口重定向到此地址</param>
public static void Confirm(string qstr, string toUrl, string backUrl)
{
HttpResponse response = HttpContext.Current.Response;
response.Write("<script language=\"javascript\">if(confirm('" + qstr + "')){window.location.href='" + backUrl + "';}else{window.location.href='" + toUrl + "';}</script>");
return;
}
/// <summary>
/// 显示询问对话框并根据用户的选择关闭当前窗口,同时决定是否刷新父窗口
/// </summary>
/// <param name="qstr">要询问操作者的内容</param>
/// <param name="_close">如果为真就关闭当前窗口</param>
/// <param name="backUrl">用户选择是的情况下将当前窗口重定向到此地址</param>
/// <param name="_refresh">在用户选择否的情况下关闭当前窗口,如果_refresh为true则刷新父窗口,否则不刷新父窗口</param>
public static void Confirm(string qstr, int _close, string backUrl, bool _refresh)
{
HttpResponse response = HttpContext.Current.Response;
if (_refresh)
{
response.Write("<script language='javascript'>if(confirm('" + qstr + "')){window.location.href='" + backUrl + "';}else{window.close();opener.location.reload();}</script>");
}
else
response.Write("<script language='javascript'>if(confirm('" + qstr + "')){window.location.href='" + backUrl + "';}else{window.close();}</script>");
return;
}
/// <summary>
/// 提示用户并刷新当前窗口
/// </summary>
/// <param name="parm">要提示用户的内容</param>
public static void Refresh(string parm)
{
HttpResponse response = HttpContext.Current.Response;
response.Write(string.Format("<script language=\"javascript\">alert('{0}');window.location.href=window.location.href;</script>", parm));
return;
}
/// <summary>
/// 提示用户并取消当前操作
/// </summary>
/// <param name="parm">提示用户的内容</param>
public static void Back(string parm)
{
HttpResponse response = HttpContext.Current.Response;
response.Write(string.Format("<script language=\"javascript\">alert('{0}');history.go(-1);</script>", parm));
return;
}
/// <summary>
/// 重定向到 url
/// </summary>
/// <param name="url"></param>
public static void toUrl(string url)
{
HttpResponse response = HttpContext.Current.Response;
response.Write(string.Format("<script language=\"javascript\">window.location.href='{0}';</script>", url));
return;
}
/// <summary>
/// 重定向到 url
/// </summary>
/// <param name="url"></param>
public static void toUrl(string parm, string url)
{
HttpResponse response = HttpContext.Current.Response;
response.Write(string.Format("<script language=\"javascript\">alert('{1}');window.location.href='{0}';</script>", url, parm));
response.Flush();
return;
}
}
--------------------------------------------------------------------------------------------------------------
libUtil.cs
#region public sealed class libUtil
public sealed class libUtil
{
private static readonly libUtil libutil = new libUtil();
public static libUtil Instance
{
get { return libutil; }
}
private int codeLen = 4;
// 图片清晰度
private int fineness = 96;
// 图片宽度
private int imgWidth = 48;
// 图片高度
private int imgHeight = 18;
// 字体家族名称
private string fontFamily = "Times New Roman";
// 字体大小
private int fontSize = 12;
// 字体样式
private int fontStyle = 1;
// 绘制起始坐标 X
private int posX = 5;
// 绘制起始坐标 Y
private int posY = 0;
// 图片背景色
private Color pbgColor = Color.FromArgb(236, 245, 252);
// 字体颜色
private Brush fontBrushe = Brushes.Firebrick;
/// <summary>
/// 产生包含验证数字的图片并将数字保存在 Session 之中
/// </summary>
public void GenerateNums()
{
GenerateNums("confirm");
}
//----------------------------------------------------------
// 创建随机验证码
//----------------------------------------------------------
private string CreateValidateCode(string sessionkey)
{
string Vchar = "0,1,2,3,4,5,6,7,8,9";
char[] sp = (",").ToCharArray();
string[] VcArray = Vchar.Split(sp);
string VNum = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeLen; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(9);
if (temp != -1 && temp == t)
{
return CreateValidateCode(sessionkey);
}
temp = t;
VNum += VcArray[t];
}
// 保存验证码
HttpContext.Current.Session[sessionkey] = VNum;
return VNum;
}
//------------------------------------------------------------
// 为图片设置干扰点
//------------------------------------------------------------
private void DisturbBitmap(Bitmap bitmap)
{
// 通过随机数生成
Random random = new Random();
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
if (random.Next(100) <= this.fineness)
bitmap.SetPixel(i, j, pbgColor);
}
}
}
//------------------------------------------------------------
// 绘制验证码图片
//------------------------------------------------------------
private void DrawValidateCode(Bitmap bitmap, string validateCode)
{
// 获取绘制器对象
Graphics g = Graphics.FromImage(bitmap);
// 设置绘制字体
Font font = new Font(fontFamily, fontSize, GetFontStyle());
// 绘制验证码图像
g.DrawString(validateCode, font, fontBrushe, posX, posY);
}
//------------------------------------------------------------
// 换算验证码字体样式:1 粗体 2 斜体 3 粗斜体,默认为普通字体
//------------------------------------------------------------
private FontStyle GetFontStyle()
{
if (fontStyle == 1)
return FontStyle.Bold;
else if (fontStyle == 2)
return FontStyle.Italic;
else if (fontStyle == 3)
return FontStyle.Bold | FontStyle.Italic;
else
return FontStyle.Regular;
}
public void GenerateNums(string sessionkey)
{
string validateCode = CreateValidateCode(sessionkey);
// 生成BITMAP图像
Bitmap bitmap = new Bitmap(imgWidth, imgHeight);
// 给图像设置干扰
DisturbBitmap(bitmap);
// 绘制验证码图像
DrawValidateCode(bitmap, validateCode);
// 保存验证码图像,等待输出
bitmap.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Gif);
}
}
#endregion
--------------------------------------------------------------------------------------------------------------
utils.cs
/// <summary>
/// 工具类
/// </summary>
public class Utils
{
public Utils() { }
/// <summary>
/// 截取字符串,中文为2个字节的长度
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns></returns>
public static int GetStringLength(string str)
{
return Encoding.Default.GetBytes(str).Length;
}
public static string GetSubString(string str, int length)
{
return "";
}
/// <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)
{
if (string.IsNullOrEmpty(p_SrcString))
return "";
string myResult = p_SrcString;
if (p_Length >= 0)
{
byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
if (bsSrcString.Length > p_Length)
{
int nRealLength = p_Length;
int[] anResultFlag = new int[p_Length];
byte[] bsResult = null;
int nFlag = 0;
for (int i = 0; i < p_Length; i++)
{
if (bsSrcString[i] > 127)
{
nFlag++;
if (nFlag == 3)
{
nFlag = 1;
}
}
else
{
nFlag = 0;
}
anResultFlag[i] = nFlag;
}
if ((bsSrcString[p_Length - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
{
nRealLength = p_Length + 1;
}
bsResult = new byte[nRealLength];
Array.Copy(bsSrcString, bsResult, nRealLength);
myResult = Encoding.Default.GetString(bsResult);
myResult = myResult + p_TailString;
}
}
return myResult;
}
/// <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);
}
/// <summary>
/// 删除字符串尾部的回车/换行/空格
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string RTrim(string str)
{
for (int i = str.Length; i >= 0; i--)
{
if (str[i].Equals(" ") || str[i].Equals("\r") || str[i].Equals("\n"))
{
str.Remove(i, 1);
}
}
return str;
}
/// <summary>
/// 清除给定字符串中的回车及换行符
/// </summary>
/// <param name="str">要清除的字符串</param>
/// <returns>清除后返回的字符串</returns>
public static string ClearBR(string str)
{
Regex r = null;
Match m = null;
r = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
for (m = r.Match(str); m.Success; m = m.NextMatch())
{
str = str.Replace(m.Groups[0].ToString(), "");
}
return str;
}
/// <summary>
/// 从字符串的指定位置截取指定长度的子字符串
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="startIndex">子字符串的起始位置</param>
/// <param name="length">子字符串的长度</param>
/// <returns>子字符串</returns>
public 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;
}
try
{
return str.Substring(startIndex, length);
}
catch
{
return str;
}
}
/// <summary>
/// 从字符串的指定位置开始截取到字符串结尾的了符串
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="startIndex">子字符串的起始位置</param>
/// <returns>子字符串</returns>
public static string CutString(string str, int startIndex)
{
return CutString(str, startIndex, str.Length);
}
/// <summary>
/// 返回文件是否存在
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>是否存在</returns>
public static bool FileExists(string filename)
{
return System.IO.File.Exists(filename);
}
/// <summary>
/// 判断文件名是否为浏览器可以直接显示的图片文件名
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>是否可以直接显示</returns>
public static bool IsImgFilename(string filename)
{
filename = filename.Trim();
if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
{
return false;
}
string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
}
/// <summary>
/// int型转换为string型
/// </summary>
/// <returns>转换后的string类型结果</returns>
public static string IntToStr(int intValue)
{
//
return Convert.ToString(intValue);
}
/// <summary>
/// MD5函数---32位
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns>MD5结果</returns>
public static string MD5(string str)
{
byte[] b = Encoding.Default.GetBytes(str);
b = new MD5CryptoServiceProvider().ComputeHash(b);
string ret = "";
for (int i = 0; i < b.Length; i++)
ret += b[i].ToString("x").PadLeft(2, '0');
return ret;
}
/// <summary>
/// SHA256函数---44位
/// </summary>
/// /// <param name="str">原始字符串</param>
/// <returns>SHA256结果</returns>
public static string SHA256(string str)
{
byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
SHA256Managed Sha256 = new SHA256Managed();
byte[] Result = Sha256.ComputeHash(SHA256Data);
return Convert.ToBase64String(Result); //返回长度为44字节的字符串
}
/// <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>
/// 生成指定数量的html空格符号
/// </summary>
public static string Spaces(int nSpaces)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nSpaces; i++)
{
sb.Append(" ");
}
return sb.ToString();
}
/// <summary>
/// 检测是否符合email格式
/// </summary>
/// <param name="strEmail">要判断的email字符串</param>
/// <returns>判断结果</returns>
public static bool IsValidEmail(string strEmail)
{
return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
/// <summary>
/// 获取email的@的后面的字符串
/// </summary>
/// <param name="strEmail">email</param>
/// <returns></returns>
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>
/// 检测是否有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\<\>\&]|$guestexp/is");
}
/// <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>
public static string[] Monthes
{
get
{
return new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
}
}
/// <summary>
/// 替换回车换行符为html换行符
/// </summary>
public static string StrFormat(string str)
{
string str2;
if (str == null)
{
str2 = "";
}
else
{
str = str.Replace("\r\n", "<br />");
str = str.Replace("\n", "<br />");
str2 = str;
}
return str2;
}
/// <summary>
/// 返回指定日期格式
/// </summary>
public static string GetDate(string datetimestr, string replacestr)
{
if (datetimestr == null)
{
return replacestr;
}
if (datetimestr.Equals(""))
{
return replacestr;
}
try
{
datetimestr = Convert.ToDateTime(datetimestr).ToString("yyyy-MM-dd").Replace("1900-01-01", replacestr);
}
catch
{
return replacestr;
}
return datetimestr;
}
/// <summary>
/// 返回标准时间格式string
/// </summary>
public static string GetTime()
{
return DateTime.Now.ToString("HH:mm:ss");
}
/// <summary>
/// 返回标准时间格式string
/// </summary>
public static string GetDateTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
/// <summary>
/// 返回相对于当前时间的相对天数
/// </summary>
public static string GetDateTime(int relativeday)
{
return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
}
/// <summary>
/// 返回标准时间格式string
/// </summary>
public static string GetDateTimeF()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
}
/// <summary>
/// 返回标准时间
/// </sumary>
public static string GetStandardDateTime(string fDateTime, string formatStr)
{
DateTime s = Convert.ToDateTime(fDateTime);
return s.ToString(formatStr);
}
/// <summary>
/// 返回标准时间 yyyy-MM-dd HH:mm:ss
/// </sumary>
public static string GetStandardDateTime(string fDateTime)
{
return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
}
/// <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)
{
string str2;
if (str == null)
{
str2 = "";
}
else
{
str = str.Replace("\'", "'");
str2 = str;
}
return str2;
}
/// <summary>
/// 替换sql语句中的有问题符号
/// </summary>
public static string ChkSQL(string str)
{
string str2;
if (str == null)
{
str2 = "";
}
else
{
str = str.Replace("'", "''");
str2 = str;
}
return str2;
}
/// <summary>
/// 分割字符串
/// </summary>
public static string[] SplitString(string strContent, string strSplit)
{
if (strContent.IndexOf(strSplit) < 0)
{
string[] tmp = { strContent };
return tmp;
}
return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase);
}
/// <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>
/// 清理'<'+'>的所有字符 ,<div>mxw</div>ssss return ==ssss
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string ClearHtml(string strHtml)
{
if (strHtml != "")
{
Regex r = null;
Match m = null;
r = new Regex(@"<\/?[^>]*>", RegexOptions.IgnoreCase);
for (m = r.Match(strHtml); m.Success; m = m.NextMatch())
{
strHtml = strHtml.Replace(m.Groups[0].ToString(), "");
}
}
return strHtml;
}
/// <summary>
/// 进行指定的替换(脏字过滤)
/// </summary>
public static string StrFilter(string str, string bantext)
{
string text1 = "";
string 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>
/// 获得伪静态页码显示链接
/// </summary>
/// <param name="curPage">当前页数</param>
/// <param name="countPage">总页数</param>
/// <param name="url">超级链接地址</param>
/// <param name="extendPage">周边页码显示个数上限</param>
/// <returns>页码html</returns>
public static string GetStaticPageNumbers(int curPage, int countPage, string url, string expname, int extendPage)
{
int startPage = 1;
int endPage = 1;
string t1 = "<a href=\"" + url + "-1" + expname + "\">«</a> ";
string t2 = "<a href=\"" + url + "-" + countPage + expname + "\">»</a> ";
if (countPage < 1) countPage = 1;
if (extendPage < 3) extendPage = 2;
if (countPage > extendPage)
{
if (curPage - (extendPage / 2) > 0)
{
if (curPage + (extendPage / 2) < countPage)
{
startPage = curPage - (extendPage / 2);
endPage = startPage + extendPage - 1;
}
else
{
endPage = countPage;
startPage = endPage - extendPage + 1;
t2 = "";
}
}
else
{
endPage = extendPage;
t1 = "";
}
}
else
{
startPage = 1;
endPage = countPage;
t1 = "";
t2 = "";
}
StringBuilder s = new StringBuilder("");
s.Append(t1);
for (int i = startPage; i <= endPage; i++)
{
if (i == curPage)
{
s.Append(" ");
s.Append(i);
s.Append(" ");
}
else
{
s.Append(" <a href=\"");
s.Append(url);
s.Append("-");
s.Append(i);
s.Append(expname);
s.Append("\">");
s.Append(i);
s.Append("</a> ");
}
}
s.Append(t2);
return s.ToString();
}
/// <summary>
/// 获得帖子的伪静态页码显示链接
/// </summary>
/// <param name="expname"></param>
/// <param name="countPage">总页数</param>
/// <param name="url">超级链接地址</param>
/// <param name="extendPage">周边页码显示个数上限</param>
/// <returns>页码html</returns>
public static string GetPostPageNumbers(int countPage, string url, string expname, int extendPage)
{
int startPage = 1;
int endPage = 1;
int curPage = 1;
string t1 = "<a href=\"" + url + "-1" + expname + "\">«</a> ";
string t2 = "<a href=\"" + url + "-" + countPage + expname + "\">»</a> ";
if (countPage < 1) countPage = 1;
if (extendPage < 3) extendPage = 2;
if (countPage > extendPage)
{
if (curPage - (extendPage / 2) > 0)
{
if (curPage + (extendPage / 2) < countPage)
{
startPage = curPage - (extendPage / 2);
endPage = startPage + extendPage - 1;
}
else
{
endPage = countPage;
startPage = endPage - extendPage + 1;
t2 = "";
}
}
else
{
endPage = extendPage;
t1 = "";
}
}
else
{
startPage = 1;
endPage = countPage;
t1 = "";
t2 = "";
}
StringBuilder s = new StringBuilder("");
s.Append(t1);
for (int i = startPage; i <= endPage; i++)
{
s.Append(" <a href=\"");
s.Append(url);
s.Append("-");
s.Append(i);
s.Append(expname);
s.Append("\">");
s.Append(i);
s.Append("</a> ");
}
s.Append(t2);
return s.ToString();
}
/// <summary>
/// 获得页码显示链接
/// </summary>
/// <param name="curPage">当前页数</param>
/// <param name="countPage">总页数</param>
/// <param name="url">超级链接地址</param>
/// <param name="extendPage">周边页码显示个数上限</param>
/// <returns>页码html</returns>
public static string GetPageNumbers(int curPage, int countPage, string url, int extendPage)
{
int startPage = 1;
int endPage = 1;
if (url.IndexOf("?") > 0)
{
url = url + "&";
}
else
{
url = url + "?";
}
string t1 = "<a href=\"" + url + "&page=1" + "\">«</a> ";
string t2 = "<a href=\"" + url + "&page=" + countPage + "\">»</a> ";
if (countPage < 1) countPage = 1;
if (extendPage < 3) extendPage = 2;
if (countPage > extendPage)
{
if (curPage - (extendPage / 2) > 0)
{
if (curPage + (extendPage / 2) < countPage)
{
startPage = curPage - (extendPage / 2);
endPage = startPage + extendPage - 1;
}
else
{
endPage = countPage;
startPage = endPage - extendPage + 1;
t2 = "";
}
}
else
{
endPage = extendPage;
t1 = "";
}
}
else
{
startPage = 1;
endPage = countPage;
t1 = "";
t2 = "";
}
StringBuilder s = new StringBuilder("");
s.Append(t1);
for (int i = startPage; i <= endPage; i++)
{
if (i == curPage)
{
s.Append(" ");
s.Append(i);
s.Append(" ");
}
else
{
s.Append(" <a href=\"");
s.Append(url);
s.Append("page=");
s.Append(i);
s.Append("\">");
s.Append(i);
s.Append("</a> ");
}
}
s.Append(t2);
return s.ToString();
}
/// <summary>
/// 返回指定目录下的非 UTF8 字符集文件
/// </summary>
/// <param name="Path">路径</param>
/// <returns>文件名的字符串数组</returns>
public static string[] FindNoUTF8File(string Path)
{
//System.IO.StreamReader reader = null;
StringBuilder filelist = new StringBuilder();
DirectoryInfo Folder = new DirectoryInfo(Path);
//System.IO.DirectoryInfo[] subFolders = Folder.GetDirectories();
/*
for (int i=0;i<subFolders.Length;i++)
{
FindNoUTF8File(subFolders[i].FullName);
}
*/
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>
/// 格式化字节数字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string FormatBytesStr(int bytes)
{
if (bytes > 1073741824)
{
return ((double)(bytes / 1073741824)).ToString("0") + "G";
}
if (bytes > 1048576)
{
return ((double)(bytes / 1048576)).ToString("0") + "M";
}
if (bytes > 1024)
{
return ((double)(bytes / 1024)).ToString("0") + "K";
}
return bytes.ToString() + "Bytes";
}
/// <summary>
/// 将long型数值转换为Int32类型
/// </summary>
/// <param name="objNum"></param>
/// <returns></returns>
public static int SafeInt32(object objNum)
{
if (objNum == null)
{
return 0;
}
string strNum = objNum.ToString();
if (IsNumber(strNum))
{
if (strNum.ToString().Length > 9)
{
return int.MaxValue;
}
return Int32.Parse(strNum);
}
else
{
return 0;
}
}
/// <summary>
/// 返回相差的秒数
/// </summary>
/// <param name="Time"></param>
/// <param name="Sec"></param>
/// <returns></returns>
public static int StrDateDiffSeconds(string Time, int Sec)
{
TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec);
if (ts.TotalSeconds > int.MaxValue)
{
return int.MaxValue;
}
else if (ts.TotalSeconds < int.MinValue)
{
return int.MinValue;
}
return (int)ts.TotalSeconds;
}
/// <summary>
/// 返回相差的分钟数
/// </summary>
/// <param name="time"></param>
/// <param name="minutes"></param>
/// <returns></returns>
public static int StrDateDiffMinutes(string time, int minutes)
{
if (time == "" || time == null)
return 1;
TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes);
if (ts.TotalMinutes > int.MaxValue)
{
return int.MaxValue;
}
else if (ts.TotalMinutes < int.MinValue)
{
return int.MinValue;
}
return (int)ts.TotalMinutes;
}
/// <summary>
/// 返回相差的小时数
/// </summary>
/// <param name="time"></param>
/// <param name="hours"></param>
/// <returns></returns>
public static int StrDateDiffHours(string time, int hours)
{
if (time == "" || time == null)
return 1;
TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours);
if (ts.TotalHours > int.MaxValue)
{
return int.MaxValue;
}
else if (ts.TotalHours < int.MinValue)
{
return int.MinValue;
}
return (int)ts.TotalHours;
}
/// <summary>
/// 为脚本替换特殊字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReplaceStrToScript(string str)
{
str = str.Replace("\\", "\\\\");
str = str.Replace("'", "\\'");
str = str.Replace("\"", "\\\"");
return str;
}
/// <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?)$");
}
/// <summary>
/// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
/// </summary>
/// <param name="ip"></param>
/// <param name="iparray"></param>
/// <returns></returns>
public static bool InIPArray(string ip, string[] iparray)
{
string[] userip = Utils.SplitString(ip, @".");
for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
{
string[] tmpip = Utils.SplitString(iparray[ipIndex], @".");
int r = 0;
for (int i = 0; i < tmpip.Length; i++)
{
if (tmpip[i] == "*")
{
return true;
}
if (userip.Length > i)
{
if (tmpip[i] == userip[i])
{
r++;
}
else
{
break;
}
}
else
{
break;
}
}
if (r == 4)
{
return true;
}
}
return false;
}
/// <summary>
/// 获得Assembly版本号
/// </summary>
/// <returns></returns>
public static string GetAssemblyVersion()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(myAssembly.Location);
return string.Format("{0}.{1}.{2}", myFileVersion.FileMajorPart, myFileVersion.FileMinorPart, myFileVersion.FileBuildPart);
}
/// <summary>
/// 获得Assembly产品名称
/// </summary>
/// <returns></returns>
public static string GetAssemblyProductName()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(myAssembly.Location);
return myFileVersion.ProductName;
}
/// <summary>
/// 获得Assembly产品版权
/// </summary>
/// <returns></returns>
public static string GetAssemblyCopyright()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(myAssembly.Location);
return myFileVersion.LegalCopyright;
}
/// <summary>
/// 判断字符串是否是yy-mm-dd字符串
/// </summary>
/// <param name="str">待判断字符串</param>
/// <returns>判断结果</returns>
public static bool IsDateString(string str)
{
return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
}
/// <summary>
/// 移除Html标记
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string RemoveHtml(string content)
{
string regexstr = @"<[^>]*>";
return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
}
/// <summary>
/// string型转换为int型
/// </summary>
/// <param name="strValue">要转换的字符串</param>
/// <param name="defValue">缺省值</param>
/// <returns>转换后的int类型结果</returns>
public static int StrToInt(object strValue, int defValue)
{
if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10))
{
return defValue;
}
string val = strValue.ToString();
string firstletter = val[0].ToString();
if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1)
{
return defValue;
}
else if (val.Length == 10 && !IsNumber(firstletter))
{
return defValue;
}
int intValue = defValue;
if (strValue != null)
{
bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString());
if (IsInt)
{
intValue = Convert.ToInt32(strValue);
}
}
return intValue;
}
/// <summary>
/// string型转换为float型
/// </summary>
/// <param name="strValue">要转换的字符串</param>
/// <param name="defValue">缺省值</param>
/// <returns>转换后的int类型结果</returns>
public static float StrToFloat(object strValue, float defValue)
{
if ((strValue == null) || (strValue.ToString().Length > 10))
{
return defValue;
}
float intValue = defValue;
if (strValue != null)
{
bool IsFloat = new Regex(@"^([-]|[0-9])[0-9]*(\.\w*)?$").IsMatch(strValue.ToString());
if (IsFloat)
{
intValue = Convert.ToSingle(strValue);
}
}
return intValue;
}
/// <summary>
/// 判断给定的字符串(strNumber)是否是数值型
/// </summary>
/// <param name="strNumber">要确认的字符串</param>
/// <returns>是则返加true 不是则返回 false</returns>
public static bool IsNumber(string strNumber)
{
return new Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber);
/*
Regex objNotNumberPattern=new Regex("[^0-9.-]");
Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
string strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
string strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");
return !objNotNumberPattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber) &&
!objTwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);
*/
}
/// <summary>
/// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型
/// </summary>
/// <param name="strNumber">要确认的字符串数组</param>
/// <returns>是则返加true 不是则返回 false</returns>
public static bool IsNumberArray(string[] strNumber)
{
if (strNumber == null)
{
return false;
}
if (strNumber.Length < 1)
{
return false;
}
foreach (string id in strNumber)
{
if (!IsNumber(id))
{
return false;
}
}
return true;
}
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
switch (mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
/// <param name="mode">生成缩略图的方式</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, string imgFormat)
{
System.Drawing.Image originalImage;
try
{
originalImage = System.Drawing.Image.FromFile(originalImagePath);
}
catch
{
return;
}
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
if (ow == 0 || oh == 0)
return;
switch (mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);
try
{
switch (imgFormat)
{
case ".jpg":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".gif":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
break;
case ".bmp":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp);
break;
case ".png":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
break;
default:
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
}
}
catch
{
//throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
}
--------------------------------------------------------------------------------------------------------------
WebBase.cs
/// <summary>
/// 供 web 层调用的通用方法提供类
/// </summary>
public sealed class WebUtil
{
/// <summary>
/// 去除特殊字符串
/// </summary>
/// <param name="Htmlstring"></param>
/// <returns></returns>
public static string DelHTML(string Htmlstring)//将HTML去除
{
#region
//删除脚本
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, @"&#(\d+);", "", RegexOptions.IgnoreCase);
Htmlstring.Replace("<", "");
Htmlstring.Replace(">", "");
Htmlstring.Replace("\r\n", "");
#endregion
return Htmlstring;
}
///手机号码验证 db 2012-9-25
public static bool IsHandset(string str_handset)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_handset, @"^[1]+[3,5,8]+\d{9}");
}
/// <summary>
/// 根据指定长度检查字符串是否符合要求
/// </summary>
/// <param name="text">需要检查的字符串</param>
/// <param name="maxLength">当前允许的最大长度</param>
/// <returns>符合长度要求的字符串</returns>
#region public static string InputText(string text, int maxLength)
public static string InputText(string text, int maxLength)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
if (text.Length > maxLength)
return text.Substring(0, maxLength);
return text;
}
#endregion
/// <summary>
/// 返回指定长度的字符串
/// </summary>
/// <param name="str"></param>
/// <param name="len"></param>
/// <returns></returns>
#region public static string Substring(object obj, int len)
public static string Substring(object obj, int len)
{
string str = obj as string;
if (string.IsNullOrEmpty(str))
return string.Empty;
if (str.Length >= len)
return str.Substring(0, len) + "…";
else
return str.Substring(0, str.Length);
//下面这个更好,中文为二,英文为一
//Encoding.Default.GetBytes(obj.ToString()).Length;
}
#endregion
/// <summary>
/// 判断是否全部为数字
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
#region public static bool IsDigit(object obj)
public static bool IsDigit(object obj)
{
if (null == obj) return false;
foreach (char ch in obj.ToString())
if (!char.IsDigit(ch)) return false;
return true;
}
#endregion
/// <summary>
/// 返回给定时间距现在时间间隔,单位为年
/// </summary>
/// <param name="dt">给定时间</param>
/// <returns><距现在时间间隔/returns>
#region public static double YearsByTime(string dt)
public static double YearsByTime(string dt)
{
if (dt != null)
{
return Math.Ceiling(((TimeSpan)(DateTime.Now - DateTime.Parse(dt))).Days / 365.0);
}
else
return 0;
}
#endregion
/// <summary>
/// 调用性别
/// </summary>
/// <param name="sex"></param>
/// <returns></returns>
#region public static string MemberSex(string sex)
public static string MemberSex(string sex)
{
if (sex == "0")
return "女";
else
return "男";
}
#endregion
/// <summary>
/// 根据指定长度检查字符串是否符合要求,并去除html字符
/// </summary>
/// <param name="text">需要检查的字符串</param>
/// <param name="maxLength">当前允许的最大长度</param>
/// <returns>符合长度要求的字符串</returns>
#region public static string InputTextEx(string text, int maxLength)
public static string InputTextEx(string text, int maxLength)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
if (text.Length > maxLength)
return text.Substring(0, maxLength);
text = Regex.Replace(text, "[\\s]{2,}", " "); //two or more spaces
text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //
text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //any other tags
text = text.Replace("'", "''");
return text;
}
#endregion
/// <summary>
/// 将控件绑定到指定集合
/// </summary>
/// <typeparam name="T">集合元素类型</typeparam>
/// <param name="rpt">repeater 参数</param>
/// <param name="list">集合</param>
#region public static void CtrlToList<T>(Repeater rpt, List<T> list) where T: new()
public static void CtrlToList<T>(Repeater rpt, List<T> list) where T : new()
{
rpt.DataSource = list;
rpt.DataBind();
}
#endregion
/// <summary>
/// 将控件绑定到指定集合
/// </summary>
/// <typeparam name="T">集合元素类型</typeparam>
/// <param name="rpt">repeater 参数</param>
/// <param name="list">集合</param>
#region public static void CtrlToList<T>(Repeater rpt, IList<T> list) where T: new()
public static void CtrlToList<T>(Repeater rpt, IList<T> list) where T : new()
{
rpt.DataSource = list;
rpt.DataBind();
}
#endregion
/// <summary>
/// 将下拉列表绑定到指定集合
/// </summary>
/// <typeparam name="T">集合元素类型</typeparam>
/// <param name="drp">下拉列表</param>
/// <param name="list">集合</param>
/// <param name="disMember">显示元素</param>
/// <param name="valMember">值元素</param>
#region public static void DrpToList<T>(DropDownList drp, List<T> list, string disMember, string valMember) where T : new()
public static void DrpToList<T>(DropDownList drp, List<T> list, string disMember, string valMember) where T : new()
{
drp.Items.Clear();
drp.DataSource = list;
drp.DataTextField = disMember;
drp.DataValueField = valMember;
drp.DataBind();
}
#endregion
/// <summary>
/// 将下拉列表绑定到指定集合并添加默认项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="drp"></param>
/// <param name="list"></param>
/// <param name="disMember"></param>
/// <param name="valMember"></param>
#region public static void DrpToListEx<T>(DropDownList drp, List<T> list, string disMember, string valMember) where T : new()
public static void DrpToListEx<T>(DropDownList drp, List<T> list, string disMember, string valMember) where T : new()
{
drp.Items.Clear();
drp.DataSource = list;
drp.DataTextField = disMember;
drp.DataValueField = valMember;
drp.DataBind();
AddEmptyItem(drp, "--请选择--", "-1");
}
#endregion
/// <summary>
/// 将下拉列表绑定到 IList<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="drp"></param>
/// <param name="list"></param>
/// <param name="disMember"></param>
/// <param name="valMember"></param>
#region public static void DrpToListEx<T>(DropDownList drp, IList<T> list, string disMember, string valMember) where T : new()
public static void DrpToListEx<T>(DropDownList drp, IList<T> list, string disMember, string valMember) where T : new()
{
drp.Items.Clear();
drp.DataSource = list;
drp.DataTextField = disMember;
drp.DataValueField = valMember;
drp.DataBind();
AddEmptyItem(drp, "--请选择--", "-1");
}
#endregion
/// <summary>
/// 向下拉列表框添加新数据
/// </summary>
/// <param name="drp">下拉列表框</param>
/// <param name="strText">文本</param>
/// <param name="strValue">值</param>
#region public static void AddEmptyItem(DropDownList drp, string strText, string strValue)
public static void AddEmptyItem(DropDownList drp, string strText, string strValue)
{
drp.Items.Insert(0, new ListItem(strText, strValue));
}
#endregion
/// <summary>
/// 将控件绑定到实现 IList 接口的集合
/// </summary>
/// <param name="rpt"></param>
/// <param name="list"></param>
#region public static void CtrlToIList(Repeater rpt, IList list)
public static void CtrlToIList(Repeater rpt, IList list)
{
rpt.DataSource = list;
rpt.DataBind();
}
#endregion
/// <summary>
/// 将控件绑定到实现 IList 接口的集合
/// </summary>
/// <param name="rpt"></param>
/// <param name="list"></param>
#region public static void CtrlToIList(Repeater rpt, IList list)
public static void CtrlToIListDL(DataList rpt, IList list)
{
rpt.DataSource = list;
rpt.DataBind();
}
#endregion
/// <summary>
/// 将 下拉列表绑定到 IList
/// </summary>
/// <param name="drp"></param>
/// <param name="list"></param>
/// <param name="disMember"></param>
/// <param name="valMember"></param>
#region public static void DrpToIList(DropDownList drp, IList list, string disMember, string valMember)
public static void DrpToIList(DropDownList drp, IList list, string disMember, string valMember)
{
drp.Items.Clear();
drp.DataSource = list;
drp.DataTextField = disMember;
drp.DataValueField = valMember;
drp.DataBind();
}
#endregion
/// <summary>
/// 将 下拉列表绑定到 IList并提供默认项
/// </summary>
/// <param name="drp"></param>
/// <param name="list"></param>
/// <param name="disMember"></param>
/// <param name="valMember"></param>
#region public static void DrpToIListEx(DropDownList drp, IList list, string disMember, string valMember)
public static void DrpToIListEx(DropDownList drp, IList list, string disMember, string valMember)
{
drp.Items.Clear();
drp.DataSource = list;
drp.DataTextField = disMember;
drp.DataValueField = valMember;
drp.DataBind();
AddEmptyItem(drp, "请选择类别", "-1");
}
#endregion
/// <summary>
/// 将 下拉列表绑定到 IList并选中指定 项
/// </summary>
/// <param name="drp"></param>
/// <param name="list"></param>
/// <param name="disMember"></param>
/// <param name="valMember"></param>
#region public static void DrpToIListEx(DropDownList drp, IList list, string disMember, string valMember, string selVal)
public static void DrpToIListEx(DropDownList drp, IList list, string disMember, string valMember, string selVal)
{
drp.Items.Clear();
drp.DataSource = list;
drp.DataTextField = disMember;
drp.DataValueField = valMember;
drp.DataBind();
AddEmptyItem(drp, "--请选择--", "-1");
drp.SelectedIndex = -1;
ListItem item = drp.Items.FindByValue(selVal);
if (item != null)
item.Selected = true;
}
#endregion
public static void DrpToIListEx(DropDownList drp, IList list, string disMember, string valMember, string selVal, string hintTxt)
{
drp.Items.Clear();
drp.DataSource = list;
drp.DataTextField = disMember;
drp.DataValueField = valMember;
drp.DataBind();
AddEmptyItem(drp, hintTxt, "-1");
drp.SelectedIndex = -1;
ListItem item = drp.Items.FindByValue(selVal);
if (item != null)
item.Selected = true;
}
/// <summary>
/// 将普通富文本转化为HTML内容输出
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string OutputText(string text)
{
if (string.IsNullOrEmpty(text))
return string.Empty;
text = text.Replace(" ", " ");
text = text.Replace("\r\n", "<br>");
return text;
}
public static string OutputIp(object Ip)
{
string ip = Ip as string;
return ip.Substring(0, ip.LastIndexOf('.')) + ".*";
}
/// <summary>
/// 判断 paramarr 里面是否存在null
/// </summary>
/// <param name="paramarr">待检查的可变长度的数组</param>
/// <returns></returns>
#region public bool IsValidParams(params object[] paramarr)
public static bool IsValidParams(params object[] paramarr)
{
for (int i = 0; i < paramarr.Length; i++)
{
if (string.IsNullOrEmpty(paramarr[i] as string) || !WebUtil.IsDigit(paramarr[i]))
return false;
}
return true;
}
#endregion
/// <summary>
/// 判断 paramarr为 查询字符串名称的数组里是否存在null
/// </summary>
/// <param name="paramarr">查询字符串名称的数组</param>
/// <returns></returns>
#region public static bool IsValidParamsEx(params object[] paramarr)
public static bool IsValidParamsEx(params object[] paramarr)
{
for (int i = 0; i < paramarr.Length; i++)
{
if (string.IsNullOrEmpty(HttpContext.Current.Request[paramarr[i] as string]) || !WebUtil.IsDigit(HttpContext.Current.Request[paramarr[i] as string]))
return false;
}
return true;
}
#endregion
/// <summary>
/// 将CheckBoxList绑定到IList
/// </summary>
/// <param name="cbl"></param>
/// <param name="list"></param>
/// <param name="disMember"></param>
/// <param name="valMember"></param>
#region public static void CblToIList(CheckBoxList cbl, IList list, string disMember, string valMember)
public static void CblToIList(CheckBoxList cbl, IList list, string disMember, string valMember)
{
cbl.Items.Clear();
cbl.DataSource = list;
cbl.DataTextField = disMember;
cbl.DataValueField = valMember;
cbl.DataBind();
}
#endregion
public static void CblToIList(RadioButtonList cbl, IList list, string disMember, string valMember)
{
cbl.Items.Clear();
cbl.DataSource = list;
cbl.DataTextField = disMember;
cbl.DataValueField = valMember;
cbl.DataBind();
}
public static void CblToIList(RadioButtonList cbl, IList list, string disMember, string valMember, object selval)
{
cbl.Items.Clear();
cbl.DataSource = list;
cbl.DataTextField = disMember;
cbl.DataValueField = valMember;
cbl.DataBind();
cbl.SelectedValue = selval.ToString();
}
#region public static void CblToIListEx(CheckBoxList cbl, IList list, string disMember, string valMember, params int[] typeArr)
public static void CblToIListEx(CheckBoxList cbl, IList list, string disMember, string valMember, IEnumerable typeArr)
{
cbl.Items.Clear();
cbl.DataSource = list;
cbl.DataTextField = disMember;
cbl.DataValueField = valMember;
cbl.DataBind();
System.Collections.IEnumerator myEnumerator = typeArr.GetEnumerator();
while (myEnumerator.MoveNext())
{
ListItem item = cbl.Items.FindByValue(myEnumerator.Current.ToString());
if (item != null)
item.Selected = true;
}
}
#endregion
/// <summary>
/// 全角转换成半角
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
#region 全角转换成半角
public static string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] - 65248);
}
return new string(c);
}
#endregion
/// <summary>
/// 星级
/// </summary>
/// <param name="grade"></param>
/// <returns></returns>
public static string ShowGrade(string grade)
{
string returnGrade = "";
switch (grade)
{
case "1":
returnGrade = "★";
break;
case "2":
returnGrade = "★★";
break;
case "3":
returnGrade = "★★★";
break;
case "4":
returnGrade = "★★★★";
break;
case "5":
returnGrade = "★★★★★";
break;
}
return returnGrade;
}
public static string ShowMessage(string cl)
{
string result = string.Empty;
switch (int.Parse(cl))
{
case 0:
result = "等待回复";
break;
case 1:
result = "<span class='p_text01'>成功预订</span>";
break;
case 2:
result = "预定失败";
break;
}
return result;
}
public static string ShowOrderType(string cl)
{
string result = string.Empty;
switch (int.Parse(cl))
{
case 0:
result = "<span class='text_dingwei'>定位</span>";
break;
case 1:
result = "<span class='text_dingdan'>订单</span>";
break;
case 3:
result = "<span class='text_dingdan'>补充订单</span>";
break;
case 2:
result = "<span class='text_dingwei'>补充订位</span>";
break;
}
return result;
}
public static string FilterSpecial(string strHtml)
{
string[] aryReg = { "'", "<", ">", "%", "\"\"", ",", ".", ">=", "=<", "-", "_", ";", "||", "[", "]", "&", "/", "-", "|", " ", };
for (int i = 0; i < aryReg.Length; i++)
{
strHtml = strHtml.Replace(aryReg[i], string.Empty);
}
return strHtml;
}
/// <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)
{
if (string.IsNullOrEmpty(p_SrcString))
return "";
string myResult = p_SrcString;
if (p_Length >= 0)
{
byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
if (bsSrcString.Length > p_Length)
{
int nRealLength = p_Length;
int[] anResultFlag = new int[p_Length];
byte[] bsResult = null;
int nFlag = 0;
for (int i = 0; i < p_Length; i++)
{
if (bsSrcString[i] > 127)
{
nFlag++;
if (nFlag == 3)
{
nFlag = 1;
}
}
else
{
nFlag = 0;
}
anResultFlag[i] = nFlag;
}
if ((bsSrcString[p_Length - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
{
nRealLength = p_Length + 1;
}
bsResult = new byte[nRealLength];
Array.Copy(bsSrcString, bsResult, nRealLength);
myResult = Encoding.Default.GetString(bsResult);
myResult = myResult + p_TailString;
}
}
return myResult;
}
}
#region calcCountEventHandler Declare
public delegate void calcCountEventHandler(object sender, countEventArgs e);
public class countEventArgs : EventArgs
{
int count;
public int Count
{
get { return count; }
set { count = value; }
}
public countEventArgs(int parm)
{
count = parm;
}
}
#endregion