using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Security.Cryptography;
using System.Net;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.Mail;
using System.Collections;
using System.Data; using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace PubClass
{
public class PubFunction
{
#region MD5加密
public string MD5(string DataStr)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(DataStr, " md5 " );
}
public string MD5_16(string DataStr)
{
string md5str = this .MD5(DataStr);
return md5str.Substring(8 , 16 );
}
#endregion
#region 随机字串
///
/// 生成指定长度的随机字串
///
/// 长度
/// 随机字串
public string GetRandomizedString(int len)
{
return this .GetRandomizedString(len, " all " );
}
///
/// 生成指定长度的随机字串
///
/// 长度
/// 字串取值范围
/// 随机字串
public string GetRandomizedString(int len, string codes)
{
string series;
switch (codes)
{
case " number " :
series = " 01234567890123456789 " ;
break ;
case " lower " :
series = " abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz " ;
break ;
case " upper " :
series = " ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ " ;
break ;
case " alpha " :
series = " ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz " ;
break ;
default :
series = " ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz " ;
break ;
}
if (len < 1 ) return "" ;
int olen = series.Length;
StringBuilder sb = new StringBuilder();
Random rnd = new Random();
for (int i = 0 ; i < len; i++)
{
sb.Append(series.Substring(rnd.Next( 0 , olen - 1 ), 1 ));
}
return sb.ToString();
}
#endregion
#region 删除特定字符
///
/// 清除字符串的非数字、字母(含下划线)和汉字字符
///
/// 传入参数
/// 结果字串
public string delNonePassportAllowChar(string txt)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(" [\x00-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\xFF] " );
return reg.Replace(txt, "" );
}
public bool hasIllegalPassportChar(string txt)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(" [\x00-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\xFF]{1,} " );
return reg.IsMatch(txt);
}
public string onlyAlphaAndDigit(string txt)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(" [^a-zA-Z0-9] " );
return reg.Replace(txt, "" );
}
public bool hasNoneAlphaAndDigit(string txt)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(" [^a-zA-Z0-9]{1,} " );
return reg.IsMatch(txt);
}
#endregion
#region 返回文件扩展名
///
/// 返回文件扩展名
///
/// 文件名
/// 小写扩展名
public string getFileExt(string filename)
{
int lidx = filename.LastIndexOf(" . " );
if (lidx == filename.Length - 1 ) return "" ;
string ext = "" ;
if (lidx > -1 )
{
ext = filename.Substring(lidx + 1 ).ToLower();
}
return ext;
}
#endregion
#region 截字处理(按字节算)
///
/// 截字处理(按字节算)
///
/// 原始字串
/// 字节长度
/// 结果字串
public string SubStringByByte(string str, int len)
{
char [] cc = str.ToCharArray();
int i = 0 , j = 0 , code;
for (i = 0 , j = 0 ; i < cc.Length && j < len; i++)
{
code = (int )cc[i];
if (code >= 0 && code <= 255 )
{
j ++;
}
else
{
j += 2 ;
}
}
if (i > 0 )
{
return str.Substring(0 , i);
}
else
{
return "" ;
}
}
public string SubStringByByte(string str, int len, bool ismore)
{
char [] cc = str.ToCharArray();
int i = 0 , j = 0 , code;
for (i = 0 , j = 0 ; i < cc.Length && j < len; i++)
{
code = (int )cc[i];
if (code >= 0 && code <= 255 )
{
j ++;
}
else
{
j += 2 ;
}
}
if (i > 0 )
{
if (!IsBlank(str))
{
if (CalcByteLength(str) > len)
{
return str.Substring(0 , i) + " .. " ;
}
else
{
return str.Substring(0 , i);
}
}
else
{
return str.Substring(0 , i);
}
}
else
{
return "" ;
}
}
///
/// 返回字节长度
///
/// 计算字串
/// 长度
public int CalcByteLength(string str)
{
char [] cc = str.ToCharArray();
int i = 0 , j = 0 , code;
for (i = 0 , j = 0 ; i < cc.Length; i++)
{
code = (int )cc[i];
if (code >= 0 && code <= 255 )
{
j ++;
}
else
{
j += 2 ;
}
}
return j;
}
#endregion
#region 检测字串是否是电子邮件地址格式
///
/// 检测字串是否是电子邮件地址格式
///
/// 需要检测的电子邮件地址字串
/// 是否是电子邮件地址格式
public bool IsEmail(string email)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@" \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* " );
return reg.IsMatch(email);
}
#endregion
#region 正则匹配检测
///
/// 正则匹配检测
///
/// 需要检测的字串
/// 正则表达式
/// 结果
public bool RegIsMatch(string txt, string reg)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(reg);
return regex.IsMatch(txt);
}
#endregion
#region 获取字符串字节数
public int GetStringByteLength(string str)
{
char [] cc = str.ToCharArray();
int i = 0 , j = 0 , code;
for (i = 0 , j = 0 ; i < cc.Length; i++)
{
code = (int )cc[i];
if (code >= 0 && code <= 255 )
{
j ++;
}
else
{
j += 2 ;
}
}
return j;
}
#endregion
#region 生成以日期时间为基础的不重复数字字串
private Random rnd = new Random();
///
/// 生成以日期时间为基础的不重复数字字串
///
/// 字串
public string getIdenticalStringBaseDateTime()
{
return DateTime.Now.ToString(" yyMMddHHmm " ) + rnd.Next(1000 , 9999 ).ToString();
}
///
/// 生成以日期时间为基础的不重复数字字串
///
/// 字串
public string getIdenticalStringBaseDateTime2()
{
return DateTime.Now.ToString(" yyMMddHHmmss " ) + rnd.Next(10000 , 99999 ).ToString();
}
#endregion
#region 生成以日期时间为基的SHA1加密字串
///
/// 生成以日期时间为基的SHA1加密字串
///
/// 40位的加密字串
public string GetSHA1StringBasedDateTime()
{
string source = DateTime.Now.ToString(" yyyyMMddHHss " ) + rnd.Next(10000 , 99999 ).ToString();
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, " sha1 " );
}
#endregion
#region 表单处理
///
/// 表单处理
///
/// 处理字串
/// 结果字串
public string TextareaStringToDatabase(string str)
{
StringBuilder sb = new StringBuilder(System.Web.HttpUtility.HtmlEncode(str));
sb = sb.Replace(" " ," " );
sb = sb.Replace(" \n " , " " );
return sb.ToString();
}
public string DatabaseStringToTextarea(string str)
{
StringBuilder sb = new StringBuilder(System.Web.HttpUtility.HtmlDecode(str));
sb = sb.Replace(" " , " " );
sb = sb.Replace(" " , " \n " );
return sb.ToString();
}
#endregion
#region 检测MIME字串是否是图片性质
///
/// 检测MIME字串是否是图片性质
///
///
///
public bool testMimeIsImage(string mime)
{
if (mime.Length < 7 ) return false ;
string begin = mime.Substring(0 , 6 ).ToLower();
return begin == " image/ " ;
}
#endregion
#region 检测MIME字串是否是音频性质
///
/// 检测MIME字串是否是音频性质
///
///
///
public bool testMimeIsAudio(string mime)
{
if (mime.Length < 7 ) return false ;
string begin = mime.Substring(0 , 6 ).ToLower();
return begin == " audio/ " ;
}
#endregion
#region 检测MIME字串是否是视频性质
///
/// 检测MIME字串是否是礼频性质
///
///
///
public bool testMimeIsVideo(string mime)
{
if (mime.Length < 7 ) return false ;
string begin = mime.Substring(0 , 6 ).ToLower();
return begin == " video/ " ;
}
#endregion
#region 检测是否是支持的文件扩展名
///
/// 检测是否是支持的文件扩展名
///
/// 扩展名,如果是空字串,则默认都是不能通过检测
/// 扩展句列表,用|分隔,如果是空字串,则默认都是通过检测
/// 结果
public bool testIsSupportFileExtent(string ext, string extcoll)
{
if (ext == "" ) return false ;
if (extcoll == "" ) return true ;
ext = ext.Trim().ToLower();
char [] sep = { ' , ' };
string [] extarr = extcoll.Split(sep);
for (int i = 0 ; i < extarr.Length; i++)
{
if (extarr[i].Trim().ToLower() == ext) return true ;
}
return false ;
}
#endregion
#region 文字水印
///
///
///
///
///
///
public bool MakeWaterImageWord(System.Web.UI.Page page, string path, string newpath)
{
// 加文字水印,
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
// System.Drawing.Image image=System.Drawing.Image.FromStream();
Graphics g = Graphics.FromImage(image);
g.DrawImage(image, 0 , 0 , image.Width, image.Height);
Font f = new Font(" Verdana " , 16 );
Brush b = new SolidBrush(Color.BurlyWood);
string addText = " 熊猫伯伯\nhttp://www.pandabobo.cn " ;
try
{
g.DrawString(addText, f, b, 10 , 10 );
g.Dispose();
// 保存加水印过后的图片,删除原始图片
string newPath = newpath;
image.Save(newPath);
image.Dispose();
if (File.Exists(path))
{
File.Delete(path);
}
return true ;
}
catch
{
return false ;
}
}
public bool MakeWaterImageWord(System.Web.UI.Page page, string path, string newpath, System.IO.Stream stream)
{
// 加文字水印,
// System.Drawing.Image image = System.Drawing.Image.FromFile(path);
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
Graphics g = Graphics.FromImage(image);
g.DrawImage(image, 0 , 0 , image.Width, image.Height);
Font f = new Font(" Verdana " , 16 );
Brush b = new SolidBrush(Color.BurlyWood);
string addText = " 熊猫伯伯\nhttp://www.pandabobo.cn " ;
try
{
g.DrawString(addText, f, b, 10 , 10 );
g.Dispose();
// 保存加水印过后的图片,删除原始图片
string newPath = newpath;
image.Save(newPath);
image.Dispose();
if (File.Exists(path))
{
File.Delete(path);
}
return true ;
}
catch
{
return false ;
}
}
#endregion
#region 图片水印
///
/// 水印
///
///
/// 图片地址
///
public bool MakeWaterImageTwo(string copyImgPath, string path)
{
// 加图片水印
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
System.Drawing.Image copyImage = System.Drawing.Image.FromFile(copyImgPath);
// 源图
int sWidth = image.Width;
int sHeight = image.Height;
// 水印图
int wWidth = (((copyImage.Width) * (sWidth / copyImage.Width)) * 1 ) / 3 ;
int wHeight = (((copyImage.Height) * (sWidth / copyImage.Width)) * 1 ) / 3 ;
if (sHeight < (sWidth * 0.382 ))
{
wWidth = (((copyImage.Width) * (sHeight / copyImage.Height)) * 1 ) / 3 ;
wHeight = (((copyImage.Height) * (sHeight / copyImage.Height)) * 1 ) / 3 ;
}
// make Graphics.
// Graphics g = Graphics.FromImage(image);
// 新建一个bmp图片
System.Drawing.Image BMP = new System.Drawing.Bitmap(sWidth, sHeight);
// 新建一个画板
Graphics G = System.Drawing.Graphics.FromImage(BMP);
// 设置高质量插值法
G.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
// 设置高质量,低速度呈现平滑程度
G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// 清空画布并以透明背景色填充
G.Clear(Color.Transparent);
// 加载原始图片
G.DrawImage(image, new Rectangle(0 , 0 , sWidth, sHeight));
// 水印属性
float [][] matrixItems ={
new float [] {1 , 0 , 0 , 0 , 0 },
new float [] {0 , 1 , 0 , 0 , 0 },
new float [] {0 , 0 , 1 , 0 , 0 },
new float [] {0 , 0 , 0 , (float )100 /100f, 0 },
new float [] {0 , 0 , 0 , 0 , 1 }
};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
ImageAttributes MarkAttr = new ImageAttributes();
MarkAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
try
{
// G.DrawImage(copyImage, new Rectangle(image.Width-copyImage.Width, image.Height-copyImage.Height,copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel,MarkAttr);
G.DrawImage(copyImage, new Rectangle(image.Width - wWidth, image.Height - wHeight, wWidth, wHeight), 8 , 10 , copyImage.Width, copyImage.Height, GraphicsUnit.Pixel, MarkAttr);
image.Dispose();
if (File.Exists(path))
{
File.Delete(path);
}
BMP.Save(path);
BMP.Dispose();
return true ;
}
catch
{
return false ;
}
}
#endregion
#region 图片水印 2
///
/// 生成水印,可按左上、左下、右上、右下、居中、透明度生成文件,只对jpeg或jpg格式有效!
///
/// 底图
/// 水印图
/// 要保存的文件
/// 位置:左上(1)、左下(2)、右上(3)、右下(4)、居中(5)
/// 透明度(1-100)
/// bool,是否成功
public bool MakeWaterImage(string sourceFile, string waterMarkFile, string saveFile, int local, int alpha)
{
bool result;
if (!File.Exists(sourceFile) || !File.Exists(waterMarkFile)) // 如果源图或水印图不存在
return false ;
FileInfo fi = new FileInfo(sourceFile);
// 判断文件类型是否合法
if (fi.Extension.ToLower() != " .jpg " & fi.Extension.ToLower() != " .jpeg " )
return false ;
try
{
// 原图
Bitmap sImage = new Bitmap(sourceFile);
int sWidth = sImage.Width;
int sHeight = sImage.Height;
// 水印图
Bitmap wImage = new Bitmap(waterMarkFile);
int wWidth = wImage.Width;
int wHeight = wImage.Height;
// make Graphics.
Graphics g = Graphics.FromImage(sImage);
int x; // 临时变量
int y; // 监时变量
int x1 = 0 ; // 原图和水印图的宽度差,即开始绘图的X位置
int y1 = 0 ; // 原图和水印图的高度差,即开始绘图的Y位置
int w = 0 ; // 生成的水印图的宽度,即结束绘图的X位置
int h = 0 ; // 生成的水印图的高度,即结束绘图的Y位置
int al; // alpha
int rl; // Red
int gl; // Green
int bl; // Blue
// 校验透明度
if (alpha < 1 || alpha > 100 )
al = 80 ;
else
al = alpha;
if (sWidth > wWidth & sHeight > wHeight) // 如果源图比水印图大
{
switch (local)
{
case 1 : // 左上
x1 = 0 ;
y1 = 0 ;
break ;
case 2 : // 左下
x1 = 0 ;
if ((sHeight - wHeight) > 0 ) // 源图比水印图高
y1 = sHeight - wHeight;
else
y1 = sWidth;
break ;
case 3 : // 右上
y1 = 0 ;
if ((sWidth - wWidth) > 0 ) // 源图比水印图宽
x1 = sWidth - wWidth;
else
x1 = sWidth;
break ;
case 4 : // 右下
// 计算高度
if ((sHeight - wHeight) > 0 ) // 源图比水印图高
y1 = sHeight - wHeight;
else
y1 = sWidth;
// 计算宽度
if ((sWidth - wWidth) > 0 ) // 源图比水印图宽
x1 = sWidth - wWidth;
else
x1 = sWidth;
break ;
case 5 : // 居中
// 计算高度
if ((sHeight - wHeight) > 0 ) // 源图比水印图高
y1 = (sHeight - wHeight) / 2 ;
else
y1 = sWidth;
// 计算宽度
if ((sWidth - wWidth) > 0 ) // 源图比水印图宽
x1 = (sWidth - wWidth) / 2 ;
else
x1 = sWidth;
break ;
}
if ((sHeight - wHeight) > 0 )
h = wHeight;
else
h = sHeight;
if ((sWidth - wWidth) > 0 )
w = wWidth;
else
w = sWidth;
}
else // 源图比水印图小
{
x1 = 0 ;
y1 = 0 ;
w = sWidth;
h = sHeight;
}
// 开始绘图
for (x = 1 ; x < w; x++)
{
for (y = 1 ; y < h; y++)
{
al = alpha;
rl = wImage.GetPixel(x, y).R;
gl = wImage.GetPixel(x, y).G;
bl = wImage.GetPixel(x, y).B;
al = 70 ;
if (rl + 25 < 255 )
rl += 25 ;
if (gl + 25 < 255 )
gl += 25 ;
if (bl + 25 < 255 )
bl += 25 ;
g.DrawEllipse( new Pen(new SolidBrush(Color.FromArgb(al, rl, gl, bl))), x1 + x, y1 + y, 1 , 1 );
}
}
g.Save();
sImage.Save(saveFile);
result = true ;
}
catch
{
result = false ;
}
return result;
}
#endregion
#region 图片按比例缩小到指定范围
///
/// 图片按比例缩小到指定范围
///
/// 标准宽度
/// 标准高度
/// 要处理图片路径
/// 处理完毕图片路径,jpg扩展名
public bool ImgLimitedSize(int standard_width, int standard_height, string input_ImgUrl, string out_ImgUrl)
{
int Reduce_Width = 0 ; // 缩小的宽度
int Reduce_Height = 0 ; // 缩小的高度
// ===通过连接创建Image对象===
System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgUrl);
int oldWidth = oldimage.Size.Width;// 原始宽度
int oldHeight = oldimage.Size.Height;// 原始高度
System.Guid guid = oldimage.RawFormat.Guid;
if (oldWidth < standard_width && oldHeight < standard_height)
{
oldimage.Dispose();
if (input_ImgUrl != out_ImgUrl)
{
System.IO.FileInfo file = new FileInfo(input_ImgUrl);
file.CopyTo(out_ImgUrl, true );
}
return true ;
}
else
{
// 根据目标大小调整缩小后高宽
float aimpp = (float )standard_width / (float )standard_height;
float oldpp = (float )oldWidth / (float )oldHeight;
float reducepp;
if (aimpp == oldpp)
{
Reduce_Width = standard_width;
Reduce_Height = standard_height;
}
else if (aimpp > oldpp)
{
reducepp = (float )standard_height / (float )oldHeight;
Reduce_Width = Convert.ToInt32(reducepp * oldWidth);
Reduce_Height = standard_height;
}
else
{
reducepp = (float )standard_width / (float )oldWidth;
Reduce_Width = standard_width;
Reduce_Height = Convert.ToInt32(reducepp * oldHeight);
}
}
// 新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(Reduce_Width, Reduce_Height);
// 新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
// 设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
// 设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// 清空画布并以透明背景色填充
g.Clear(Color.Transparent);
// 按指定的高宽范围比例缩小图片
g.DrawImage(oldimage, new Rectangle(0 , 0 , Reduce_Width, Reduce_Height), new Rectangle(0 , 0 , oldWidth, oldHeight), GraphicsUnit.Pixel);
try
{
ImageFormat saveformat = oldimage.RawFormat;
oldimage.Dispose();
// 以原始格式保存缩略图
bitmap.Save(out_ImgUrl, saveformat);
}
catch (System.Exception e)
{
throw e;
}
finally
{
bitmap.Dispose();
g.Dispose();
}
return true ;
}
#endregion
#region 缩放图片到指定大小
///
/// 缩放图片到指定大小(需要裁剪)
///
/// 标准宽度
/// 标准高度
/// 要处理图片路径
/// 处理完毕图片路径,jpg扩展名
/// 是否成功
public bool ImgFixedSize(int standard_width, int standard_height, string input_ImgUrl, string out_ImgUrl)
{
int CutX = 0 ;// 裁剪X坐标
int CutY = 0 ;// 裁剪Y坐标
int CutWidth;// 裁剪宽度
int CutHeight;// 裁剪调试
// ===通过连接创建Image对象===
System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgUrl);
int oldWidth = oldimage.Size.Width;// 图片原始宽度
int oldHeight = oldimage.Size.Height;// 图片原始高度
System.Guid guid = oldimage.RawFormat.Guid;
float aimpp = (float )standard_width / (float )standard_height;
float oldpp = (float )oldWidth / (float )oldHeight;
if (aimpp == oldpp)
{
CutWidth = oldWidth;
CutHeight = oldHeight;
}
else if (aimpp > oldpp)
{
CutWidth = oldWidth;
CutHeight = Convert.ToInt32((float )standard_height * ((float )oldWidth / (float )standard_width));
CutX = 0 ;
CutY = (oldHeight - CutHeight) / 2 ;
}
else
{
CutWidth = Convert.ToInt32((float )standard_width * ((float )oldHeight / (float )standard_height));
CutHeight = oldHeight;
CutX = (oldWidth - CutWidth) / 2 ;
CutY = 0 ;
}
// 新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(standard_width, standard_height);
// 新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
// 设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
// 设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// 清空画布并以透明背景色填充
g.Clear(Color.Transparent);
// 在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(oldimage, new Rectangle(0 , 0 , standard_width, standard_height), new Rectangle(CutX, CutY, CutWidth, CutHeight), GraphicsUnit.Pixel);
try
{
ImageFormat saveformat = oldimage.RawFormat;
oldimage.Dispose();
// 以原始格式保存缩略图
bitmap.Save(out_ImgUrl, saveformat);
}
catch (System.Exception e)
{
throw e;
}
finally
{
bitmap.Dispose();
g.Dispose();
}
return true ;
}
#endregion
#region 缩放图片到指定的宽或高
public bool ImgLimitWidthOrHeight(int standard, string input_ImgUrl, string out_ImgUrl)
{
return ImgLimitWidthOrHeight(standard, input_ImgUrl, out_ImgUrl, " width " );
}
///
/// 缩放图片到指定的宽或高
///
/// 标准宽度
/// 要处理图片路径
/// 处理完毕图片路径
/// 指定以长或宽为标准,width或height
/// 是否成功
public bool ImgLimitWidthOrHeight(int standard, string input_ImgUrl, string out_ImgUrl, string WidthOrHeight)
{
int Reduce_Width = 0 ; // 缩小的宽度
int Reduce_Height = 0 ; // 缩小的高度
// ===通过连接创建Image对象===
System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgUrl);
int oldWidth = oldimage.Size.Width;// 原始宽度
int oldHeight = oldimage.Size.Height;// 原始高度
System.Guid guid = oldimage.RawFormat.Guid;
float aimpp;
WidthOrHeight = WidthOrHeight.ToLower().Trim();
if (WidthOrHeight == " width " )
{
aimpp = (float )standard / (float )oldWidth;
Reduce_Width = standard;
Reduce_Height = (int )((float )oldHeight * aimpp);
}
else
{
aimpp = (float )standard / (float )oldHeight;
Reduce_Width = (int )((float )oldWidth * aimpp);
Reduce_Height = standard;
}
// 新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(Reduce_Width, Reduce_Height);
// 新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
// 设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
// 设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
// 清空画布并以透明背景色填充
g.Clear(Color.Transparent);
// 按指定的高宽范围比例缩小图片
g.DrawImage(oldimage, new Rectangle(0 , 0 , Reduce_Width, Reduce_Height), new Rectangle(0 , 0 , oldWidth, oldHeight), GraphicsUnit.Pixel);
try
{
ImageFormat saveformat = oldimage.RawFormat;
oldimage.Dispose();
// 以原始格式保存缩略图
bitmap.Save(out_ImgUrl, saveformat);
}
catch (System.Exception e)
{
throw e;
}
finally
{
bitmap.Dispose();
g.Dispose();
}
return true ;
}
#endregion
#region 获取图片文件长宽
///
/// 获取图片文件长宽
///
/// 图片路径
/// 包含长宽数据的ArrayList
public ArrayList getImageWidthAndHeight(string filepath)
{
ArrayList arr = new ArrayList(2 );
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);
arr[ 0 ] = img.Width;
arr[ 1 ] = img.Height;
img.Dispose();
}
catch
{
arr[ 0 ] = -1 ;
arr[ 1 ] = -1 ;
}
return arr;
}
#endregion
#region 测试图片是否超过指定大小
///
/// 测试图片是否超过指定大小
///
/// 图片文件地址(磁盘绝对地址)
/// 指定宽
/// 指定高
/// 结果
public bool testImageOverSize(string filepath, int width, int height)
{
ArrayList wh = this .getImageWidthAndHeight(filepath);
int w = (int )wh[0 ];
int h = (int )wh[1 ];
if (w < 1 || h < 1 )
{
return true ;
}
else
{
return w > width || h > height;
}
}
#endregion
#region 创建文件夹名
///
/// 功能:创建文件名
/// 返回:文件夹名foldername
/// 编写人:简清舟
///
///
public string CreateFolderName()
{
DateTime time = System.DateTime.Now;// 取时间
string foldername = time.Year.ToString() + time.Month.ToString();// 创建文件夹名
return foldername;// 返回文件名
}
#endregion
#region 创建文件夹
///
/// 功能:创建文件夹
/// 参数:path是文件的路径
/// 编写人:简清舟
///
/// 文件路径
public bool CreateFolder(string path, Page page)
{
try
{
path = page.Server.MapPath(path);//
// 检查目录是否存在
if (Directory.Exists(path))
{
// Response.Write("目录已经存在.");
return true ;
}
// 创建目录
DirectoryInfo di = Directory.CreateDirectory(path);
// Response.Write("目录应创建成功");
// 删除目录
// di.Delete();
// Console.WriteLine("目录已经删除.");
return true ;
}
catch
{
return false ;
// Response.Write("");
}
}
#endregion
#region 删除HTML标签"<...>"
///
/// 删除字串中的HTML标签
///
/// 原始字串
/// 结果字串
public string DeleteHtmlTag(string txt)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(" <[^>]{1,}> " );
return reg.Replace(txt, "" );
}
#endregion
#region 把数字转换为以Kb或Mb或T表示的容量
///
/// 把数字转换为以Kb或Mb或T表示的容量
///
/// 数字(字节)
/// 表示方法
public string ConvertLongToVolumeString(long size)
{
double rtnvol = 0 ;
if (size < 1024 )
{
return size.ToString() + " Bit " ;
}
else if (size < 1048576 )
{
rtnvol = (double )size / 1024.0 ;
return rtnvol.ToString(" f2 " ) + " KB " ;
}
else if (size < 1073741824 )
{
rtnvol = (double )size / 1048576.0 ;
return rtnvol.ToString(" f2 " ) + " MB " ;
}
else if (size < 1099511627776 )
{
rtnvol = (double )size / 1073741824.0 ;
return rtnvol.ToString(" f2 " ) + " GB " ;
}
else
{
rtnvol = (double )size / 1099511627776.0 ;
return rtnvol.ToString(" f2 " ) + " T " ;
}
}
#endregion
#region 输出MediaPlayer播放器代码
///
/// 输出MediaPlayer播放器代码
///
/// URL
/// 是否自动播放
/// 代码
public string GetMediaPlayCodes(string url, bool auto)
{
return this .GetMediaPlayCodes(url, auto, true );
}
public string GetMediaPlayCodes(string url, bool auto, bool withSkin)
{
StringBuilder sbframe = new StringBuilder();
if (withSkin)
{
sbframe.Append( " " );
sbframe.Append( " " );
sbframe.Append( " " );
sbframe.Append( " " );
sbframe.Append( " " );
sbframe.Append( " " );
sbframe.Append( "
" );
}
else
{
sbframe.Append( " {$PlayerCode} " );
}
StringBuilder sb = new StringBuilder();
sb.Append( " \n\n " );
sbframe.Replace( " {$PlayerCode} " , sb.ToString());
return sbframe.ToString();
}
public string GetMediaPlayCodes(string url, bool auto, string mode)
{
StringBuilder sb = new StringBuilder();
sb.Append( " \n\n " );
sb.Append( " " + mode.Trim() + " \">\n " );
sb.Append( " " );
if (auto)
{
sb.Append( " -1 " );
}
else
{
sb.Append( " 0 " );
}
sb.Append( " >\n " );
sb.Append( " \n" );
sb.Append( " \n" );
sb.Append( " " + url + " \">\n " );
sb.Append( " " + url + " \" src=\" " + url + " \" Name=\"mediaplayer\" autostart=\" " + auto.ToString() + " \" ShowControls=1 ShowDisplay=0 ShowStatusBar=0 autosize=0 width=\"100%\" height=\"100%\" uiMode=\" " + mode + " \" StretchToFit=\"1\" EnableContextMenu=\"0\"> \n" );
sb.Append( " \n " );
return sb.ToString();
}
#endregion
#region 传入一字符串,返回拼音首字母
///
/// 传入一字符串,返回字串第一个字符的拼音首字母
///
/// 传入字串
/// 首字母
public string GetStringCapital(string str)
{
if (str.Length < 1 ) return "" ;
string _Temp = str.Substring(0 , 1 );
if (Convert.ToChar(_Temp) >= 0 && Convert.ToChar(_Temp) < 256 ) return _Temp;
if (_Temp.CompareTo(" 吖 " ) < 0 )
{
return str;
}
if (_Temp.CompareTo(" 八 " ) < 0 )
{
return " A " ;
}
if (_Temp.CompareTo(" 嚓 " ) < 0 )
{
return " B " ;
}
if (_Temp.CompareTo(" 咑 " ) < 0 )
{
return " C " ;
}
if (_Temp.CompareTo(" 妸 " ) < 0 )
{
return " D " ;
}
if (_Temp.CompareTo(" 发 " ) < 0 )
{
return " E " ;
}
if (_Temp.CompareTo(" 旮 " ) < 0 )
{
return " F " ;
}
if (_Temp.CompareTo(" 铪 " ) < 0 )
{
return " G " ;
}
if (_Temp.CompareTo(" 讥 " ) < 0 )
{
return " H " ;
}
if (_Temp.CompareTo(" 咔 " ) < 0 )
{
return " J " ;
}
if (_Temp.CompareTo(" 垃 " ) < 0 )
{
return " K " ;
}
if (_Temp.CompareTo(" 嘸 " ) < 0 )
{
return " L " ;
}
if (_Temp.CompareTo(" 拏 " ) < 0 )
{
return " M " ;
}
if (_Temp.CompareTo(" 噢 " ) < 0 )
{
return " N " ;
}
if (_Temp.CompareTo(" 妑 " ) < 0 )
{
return " O " ;
}
if (_Temp.CompareTo(" 七 " ) < 0 )
{
return " P " ;
}
if (_Temp.CompareTo(" 亽 " ) < 0 )
{
return " Q " ;
}
if (_Temp.CompareTo(" 仨 " ) < 0 )
{
return " R " ;
}
if (_Temp.CompareTo(" 他 " ) < 0 )
{
return " S " ;
}
if (_Temp.CompareTo(" 哇 " ) < 0 )
{
return " T " ;
}
if (_Temp.CompareTo(" 夕 " ) < 0 )
{
return " W " ;
}
if (_Temp.CompareTo(" 丫 " ) < 0 )
{
return " X " ;
}
if (_Temp.CompareTo(" 帀 " ) < 0 )
{
return " Y " ;
}
if (_Temp.CompareTo(" 咗 " ) < 0 )
{
return " Z " ;
}
return _Temp;
}
#endregion
#region 将System.Web.HttpPostedFile 转化为byte[]
///
/// 函数名称:PostedFileToBytes
/// 函数性能功能描述:将System.Web.HttpPostedFile 转化为byte[]
/// 本函数调用的类与函数清单:
///
/// byte[]
public byte [] PostedFileToBytes(System.Web.HttpPostedFile PostFile)
{
int FileSize = PostFile.ContentLength; // 大小
byte [] fileContent;// 实际文件的数据.
string FileType = PostFile.ContentType;// 发送文件的MIME内容类型
BinaryReader AttContent = new BinaryReader(PostFile.InputStream);// 获得文件的流
AttContent.BaseStream.Seek(0 , SeekOrigin.Begin);
return fileContent = AttContent.ReadBytes(FileSize);// 获得文件的字节流
}
#endregion
#region 从路径形式的字串中提取文件名
///
/// 从路径形式的字串中提取文件名
///
/// 路径
/// 是否带扩展名
/// 文件名
public string GetFileName(string path, bool withext)
{
int last = path.LastIndexOf(" \\ " );
if (last >= 0 )
{
path = path.Substring(last + 1 );
}
last = path.LastIndexOf(" . " );
if (withext || last < 0 )
{
return path;
}
else
{
return path.Substring(0 , last);
}
}
///
/// 从路径形式的字串中提取文件名
///
/// 路径
/// 文件名
public string GetFileName(string path)
{
return this .GetFileName(path, true );
}
#endregion
#region 请求internet页面Html源码
///
/// 请求并下载页面
///
/// The data downloaded from the page
public string GetPageHTML(string url)
{
string m_uri = url;
WebResponse response = null ;
Stream stream = null ;
StreamReader reader = null ;
try
{
// ----------返回被请求的internet上的资源---------
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_uri);
response = request.GetResponse();
stream = response.GetResponseStream();
// ------------------------------
if (!response.ContentType.ToLower().StartsWith(" text/ " ))// 如果类型不是text 就调用SaveBinaryFile写成二近制文件
{
// SaveBinaryFile(response); // 写二进制文件
return null ;
}
string buffer = "" , line;
reader = new StreamReader(stream, Encoding.GetEncoding(" gb2312 " ));
while ((line = reader.ReadLine()) != null )
{
buffer += line + " \r\n " ;
}
return buffer;
}
// catch(WebException e)
catch
{
return "" ;
}
// catch(IOException e)
finally
{
if (reader != null ) reader.Close();
if (stream != null ) stream.Close();
if (response != null ) response.Close();
}
}
///
/// 信息写入磁盘
///
/// 写入内容
/// 写入的实际地址和完整的文件名称
///
public bool SaveTextFile(string buffer, string Path)// 保存文本文件
{
if (Path == "" )
return false ;
string filename = Path;// 创建文件名和文件目录
try
{
StreamWriter outStream = new StreamWriter(filename, false , Encoding.GetEncoding(" gb2312 " ));
// 写磁盘
outStream.WriteLine(buffer);
outStream.Close();
return true ;
}
catch
{
return false ;
}
}
///
/// 生成静态页面
///
/// 资源页面URL地址
/// 生成的目录html文件绝对路径
/// 是否生成成功
public bool GenHTML(string url, string htmlfileAbsPath, Page page)
{
try
{
string source = this .GetPageHTML(url);
if (source.ToString() != "" )
{
this .SaveTextFile(source, htmlfileAbsPath);
return true ;
}
else
{
return false ;
}
}
catch
{
return false ;
}
}
#endregion
#region 使用正则方式替换字串
///
/// 使用正则方式替换字串
///
/// 要进行操作的字串
/// 正则字串
/// 替换字串
/// 结果字串
public string RegReplace(string txt, string reg, string replace)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(reg);
return regex.Replace(txt, replace);
}
#endregion
#region IP部分保密处理
public string IPSafe(string ip)
{
int dotStart = ip.LastIndexOf(" . " ) + 1 ;
if (dotStart < 1 ) return " 未知 " ;
int dotEnd = ip.Length;
return ip.Remove(dotStart, dotEnd - dotStart) + " * " ;
}
#endregion
#region 读取配置节
///
/// 读取配置节内容
///
/// 配置标识
/// 结果字串
public string GetAppsetting(string key)
{
try
{
return System.Configuration.ConfigurationSettings.AppSettings[key];
}
catch
{
return null ;
}
}
#endregion
#region 删除磁盘文件
///
/// 删除磁盘文件
///
/// 文件路径
///
public bool DeleteFile(string Path)
{
try
{
System.IO.File.Delete(Path);
return true ;
}
catch
{
return false ;
}
}
#endregion
#region 发送电子邮件
///
/// 发送电子邮件
///
/// 收件人地址
/// 收件人姓名
/// 邮件主题
/// 邮件正文
public bool SendMail(string EmailSendTheme, string email, string name, string subject, string body)
{
string mailsetup = this .GetAppsetting(" emailset " );
string s_object;
string s_email;
string s_name;
string s_server;
string s_passport;
string s_passkey;
try
{
char [] sep = { ' , ' };
string [] vals = mailsetup.Split(sep);
s_object = vals[0 ].Trim().ToLower();
// (1)表示发件人的E-Mail地址。该地址一般与使用SMTP服务器验证时所需的登录帐户相同。
s_email = vals[1 ].Trim();
// (2)表示发件人的名称。
s_name = vals[2 ].Trim();
// (3)可以忽略 EHLO/HELO 状态对你的mailserver
s_server = vals[3 ].Trim();
// (4)表示当邮件服务器使用SMTP发信验证时设置的登录帐户。
s_passport = vals[4 ].Trim();
// (5)表示当邮件服务器使用SMTP发信验证时设置的密码
s_passkey = vals[5 ].Trim();
}
catch
{
return false ;
}
switch (s_object)
{
case " jmail " :
jmail.MessageClass jmail = new jmail.MessageClass();
// Logging属性,表示是否启用日志
jmail.Logging = true ;
// 表示屏蔽例外错误,返回FALSE或TRUE值,当值为TRUE时,表示邮件发送会忽略错误,不将错误信息返回给操作系统。
jmail.Silent = true ;
jmail.Priority = 1 ;
jmail.Encoding = " GB2312 " ;
// 设置邮件显示的字符集,中文简体可使用utf-8
jmail.Charset = " GB2312 " ;
jmail.ISOEncodeHeaders = false ;
// 邮件主体(HTML(注意信件内链接附件的方式)) x
jmail.HTMLBody = body;
// 邮件主题
jmail.Subject = subject;
// 表示发件人的E-Mail地址。该地址一般与使用SMTP服务器验证时所需的登录帐户相同。
jmail.From = s_email;
// 表示发件人的名称。
jmail.FromName = s_name;
// 表示当邮件服务器使用SMTP发信验证时设置的登录帐户。( 身份验证 )
jmail.MailServerUserName = s_passport;
jmail.MailServerPassWord = s_passkey;
// 可以忽略 EHLO/HELO 状态对你的mailserver
jmail.MailDomain = s_server;
// 表示收件人的E-Mail地址。
jmail.AddRecipient(email, name, null );
bool result = jmail.Send(s_server, false );
jmail.Close();
return result;
case " cdo " :
System.Web.Mail.MailMessage cdomail = new MailMessage();
cdomail.To = " \" " + HttpUtility.HtmlEncode(name) + " \"< " + email + " > " ;
cdomail.From = " \" " + HttpUtility.HtmlEncode(s_name) + " \"< " + s_email + " > " ;
cdomail.BodyEncoding = Encoding.UTF8;
cdomail.BodyFormat = MailFormat.Html;
cdomail.Priority = MailPriority.High;
cdomail.Subject = subject;
cdomail.Body = body;
SmtpMail.Send(cdomail);
return true ;
case " cdo2 " :
MailMessage cdomail2 = new MailMessage();
cdomail2.To = email;
cdomail2.From = s_email;
cdomail2.Subject = subject;
cdomail2.Body = body;
cdomail2.Fields.Add( " http://schemas.microsoft.com/cdo/configuration/sendusing " , " 2 " );
cdomail2.Fields.Add( " http://schemas.microsoft.com/cdo/configuration/smtpserver " , s_server);
cdomail2.Fields.Add( " http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout " , 10 );
cdomail2.Fields.Add( " http://schemas.microsoft.com/cdo/configuration/smtpauthenticate " , " 1 " );
cdomail2.Fields.Add( " http://schemas.microsoft.com/cdo/configuration/sendusername " , s_passport);
cdomail2.Fields.Add( " http://schemas.microsoft.com/cdo/configuration/sendpassword " , s_passkey);
SmtpMail.Send(cdomail2);
return true ;
default :
return false ;
}
}
#endregion
#region 替换非法字符
public string Sqlstring(string str)
{
if (str != null && str != "" )
{
str = str.Replace(" ' " , "" );
str = str.Replace(" \" " , "" );
str = str.Replace(" ; " , "" );
str = str.Replace(" < " , "" );
str = str.Replace(" > " , "" );
str = str.Replace(" ( " , "" );
str = str.Replace(" ) " , "" );
str = str.Replace(" * " , "" );
str = str.Replace(" -- " , "" );
str = str.Replace(" select " , "" );
str = str.Replace(" SELECT " , "" );
str = str.Replace(" insert " , "" );
str = str.Replace(" INSERT " , "" );
str = str.Replace(" update " , "" );
str = str.Replace(" UPDATE " , "" );
str = str.Replace(" delete " , "" );
str = str.Replace(" DELETE " , "" );
str = str.Replace(" create " , "" );
str = str.Replace(" CREATE " , "" );
str = str.Replace(" drop " , "" );
str = str.Replace(" DROP " , "" );
str = str.Replace(" delcare " , "" );
str = str.Replace(" DELCARE " , "" );
str = str.Replace(" truncate " , "" );
str = str.Replace(" TRUNCATE " , "" );
str = str.Replace(" script " , "" );
str = str.Replace(" SCRIPT " , "" );
// str = str.Replace("and", "");
// str = str.Replace("AND", "");
str = FilterXSS(str);
}
return str;
}
public string Sqlstring(string str, int id)
{
if (str != null && str != "" )
{
str = str.Replace(" ' " , " ’ " );
str = str.Replace(" \" " , " ” " );
str = str.Replace(" ; " , " ; " );
str = str.Replace(" < " , " [ " );
str = str.Replace(" > " , " ] " );
str = str.Replace(" ( " , " ( " );
str = str.Replace(" ) " , " ) " );
str = str.Replace(" * " , " × " );
str = str.Replace(" -- " , "" );
str = str.Replace(" \r\n " , " " );
str = str.Replace(" \n " , " " );
// str = str.Replace(" "," ");
str = str.Replace(" select " , "" );
str = str.Replace(" SELECT " , "" );
str = str.Replace(" insert " , "" );
str = str.Replace(" INSERT " , "" );
str = str.Replace(" update " , "" );
str = str.Replace(" UPDATE " , "" );
str = str.Replace(" delete " , "" );
str = str.Replace(" DELETE " , "" );
str = str.Replace(" create " , "" );
str = str.Replace(" CREATE " , "" );
str = str.Replace(" drop " , "" );
str = str.Replace(" DROP " , "" );
str = str.Replace(" delcare " , "" );
str = str.Replace(" DELCARE " , "" );
str = str.Replace(" truncate " , "" );
str = str.Replace(" TRUNCATE " , "" );
str = str.Replace(" script " , "" );
str = str.Replace(" SCRIPT " , "" );
// str = str.Replace("and", "");
// str = str.Replace("AND", "");
str = FilterXSS(str);
}
return str;
}
#endregion ;
#region 过滤xss攻击脚本
///
/// 过滤xss攻击脚本
///
/// 传入字符串
/// 过滤后的字符串
public string FilterXSS(string html)
{
if (string .IsNullOrEmpty(html)) return string .Empty;
// CR(0a) ,LF(0b) ,TAB(9) 除外,过滤掉所有的不打印出来字符.
// 目的防止这样形式的入侵 <java\0script>
// 注意:\n, \r, \t 可能需要单独处理,因为可能会要用到
string ret = System.Text.RegularExpressions.Regex.Replace(
html, " ([\x00-\x08][\x0b-\x0c][\x0e-\x20]) " , string .Empty);
// 替换所有可能的16进制构建的恶意代码
//
string chars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()~`;:?+/={}[]-_|'\"\\ " ;
for (int i = 0 ; i < chars.Length; i++)
{
ret = System.Text.RegularExpressions.Regex.Replace(ret, string .Concat(" ([x|X]0{0,} " , Convert.ToString((int )chars[i], 16 ).ToLower(), " ;?) " ),
chars[i].ToString(), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
}
// 过滤\t, \n, \r构建的恶意代码
string [] keywords = {" javascript " , " vbscript " , " expression " , " applet " , " meta " , " xml " , " blink " , " link " , " style " , " script " , " embed " , " object " , " iframe " , " frame " , " frameset " , " ilayer " , " layer " , " bgsound " , " title " , " base "
, " onabort " , " onactivate " , " onafterprint " , " onafterupdate " , " onbeforeactivate " , " onbeforecopy " , " onbeforecut " , " onbeforedeactivate " , " onbeforeeditfocus " , " onbeforepaste " , " onbeforeprint " , " onbeforeunload " , " onbeforeupdate " , " onblur " , " onbounce " , " oncellchange " , " onchange " , " onclick " , " oncontextmenu " , " oncontrolselect " , " oncopy " , " oncut " , " ondataavailable " , " ondatasetchanged " , " ondatasetcomplete " , " ondblclick " , " ondeactivate " , " ondrag " , " ondragend " , " ondragenter " , " ondragleave " , " ondragover " , " ondragstart " , " ondrop " , " onerror " , " onerrorupdate " , " onfilterchange " , " onfinish " , " onfocus " , " onfocusin " , " onfocusout " , " onhelp " , " onkeydown " , " onkeypress " , " onkeyup " , " onlayoutcomplete " , " onload " , " onlosecapture " , " onmousedown " , " onmouseenter " , " onmouseleave " , " onmousemove " , " onmouseout " , " onmouseover " , " onmouseup " , " onmousewheel " , " onmove " , " onmoveend " , " onmovestart " , " onpaste " , " onpropertychange " , " onreadystatechange " , " onreset " , " onresize " , " onresizeend " , " onresizestart " , " onrowenter " , " onrowexit " , " onrowsdelete " , " onrowsinserted " , " onscroll " , " onselect " , " onselectionchange " , " onselectstart " , " onstart " , " onstop " , " onsubmit " , " onunload " };
bool found = true ;
while (found)
{
string retBefore = ret;
for (int i = 0 ; i < keywords.Length; i++)
{
string pattern = " / " ;
for (int j = 0 ; j < keywords[i].Length; j++)
{
if (j > 0 )
pattern = string .Concat(pattern, ' ( ' , " ([x|X]0{0,8}([9][a][b]);?)? " , " |({0,8}([9][10][13]);?)? " ,
" )? " );
pattern = string .Concat(pattern, keywords[i][j]);
}
string replacement = string .Concat(keywords[i].Substring(0 , 2 ), " <x> " , keywords[i].Substring(2 ));
ret = System.Text.RegularExpressions.Regex.Replace(ret, pattern, replacement, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (ret == retBefore)
found = false ;
}
}
return ret;
}
#endregion
#region 是否空
/// 是否空
/// 输入字符串
/// true/false
public bool IsBlank(string strInput)
{
if (strInput == null || strInput.Trim() == "" )
{
return true ;
}
else
{
return false ;
}
}
#endregion
#region 是否数字
/// 是否数字
/// 输入字符串
/// true/false
private Regex RegNumber = new Regex(" ^[0-9]+$ " );
private static Regex RegDecimal = new Regex(" ^[0-9]+[.]?[0-9]+$ " );
public bool IsNumeric(string strInput)
{
if (strInput != null && strInput != "" )
{
Match m = RegNumber.Match(strInput);
return m.Success;
}
else
{
return false ;
}
}
public bool IsDecimal(string inputData)
{
if (inputData != null && inputData != "" )
{
Match m = RegNumber.Match(inputData);
if (m.Success) return m.Success;
m = RegDecimal.Match(inputData);
return m.Success;
}
else
{
return false ;
}
}
#endregion
#region 是否日期
/// 是否日期
/// 输入字符串
/// true/false
public bool isDate(string strInput)
{
try
{
if (strInput != null && strInput != "" && strInput.Length >= 8 )
{
string s = strInput.Substring(0 , 4 );
if (!IsNumeric(s) || int .Parse(s) < 1900 )
{
return false ;
}
else
{
DateTime t = Convert.ToDateTime(strInput);
return true ;
}
}
else
{
return false ;
}
}
catch
{
return false ;
}
}
#endregion
#region 是否为合法的手机号码
/// 是否为合法的手机号码
/// 输入字符串
/// true/false
private Regex RegMobile = new Regex(@" (^(13\d{9})$)|(^(15\d{9})$)|(^(18\d{9})$)|(^(14\d{9})$) " );
public bool isMobile(string strInput)
{
if (strInput != null && strInput != "" )
{
Match m = RegMobile.Match(strInput);
return m.Success;
}
else
{
return false ;
}
}
#endregion
#region 是否为合法的电话号码
/// 是否为合法的电话号码
/// 输入字符串
/// true/false
private Regex RegTEL = new Regex(@" (^(\d{7,8})$)|(^(0\d{2,3}\-\d{6,8}(\-\d{1,4})?)$) " );
public bool isTel(string strInput)
{
if (strInput != null && strInput != "" )
{
Match m = RegTEL.Match(strInput);
return m.Success;
}
else
{
return false ;
}
}
#endregion
#region 邮政编码
///
/// 是否是邮政编码
///
/// 输入字符串
///
private Regex RegZip = new Regex(@" ^(\d{6})$ " );
public bool IsZip(string inputData)
{
if (inputData != null && inputData != "" )
{
Match m = RegZip.Match(inputData);
return m.Success;
}
else
{
return false ;
}
}
#endregion
#region 是否为身份证号
///
/// 是否为身份证号
///
/// 输入字符串
///
private Regex RegIDCard = new Regex(" ^[1-9]([0-9]{17}|[0-9]{14}|[0-9]{16}[0-9,X,x])$ " );
public bool IsIDCard(string strInput)
{
if (strInput != null && strInput != "" )
{
Match m = RegIDCard.Match(strInput);
return m.Success;
}
else
{
return false ;
}
}
#endregion
#region js脚本
public void Alert(string message, int ID)
{
message = this .Sqlstring(message);
string js = @" " ;
HttpContext.Current.Response.Write(js);
}
public void Alert(string message)
{
message = this .Sqlstring(message);
string js = @" " ;
HttpContext.Current.Response.Write(js);
}
public void Alert(System.Web.UI.Page page, string message, int ID)
{
message = this .Sqlstring(message);
string js = @" " ;
page.ClientScript.RegisterStartupScript( this .GetType(), " 提示 " , js);
}
public void Alert(System.Web.UI.Page page, string message)
{
message = this .Sqlstring(message);
string js = @" " ;
page.ClientScript.RegisterStartupScript( this .GetType(), " 提示 " , js);
}
///
/// 弹出窗口,转向Url制定的页面
///
///
public void Location(string message, string url)
{
message = this .Sqlstring(message);
string js = @" " ;
js = string .Format(js, url);
HttpContext.Current.Response.Write(js);
}
///
/// 弹出窗口,转向Url制定的页面
///
///
public void Location(System.Web.UI.Page page, string message, string url)
{
message = this .Sqlstring(message);
string js = @" " ;
js = string .Format(js, url);
page.ClientScript.RegisterStartupScript( this .GetType(), " 提示 " , js);
}
///
/// 输出自定义脚本信息
///
/// 当前页面指针,一般为this
/// 输出脚本
public void ResponseScript(System.Web.UI.Page page, string script)
{
page.ClientScript.RegisterStartupScript( this .GetType(), " message " , " " + script + " " );
}
#endregion
#region 按字节截取字符串省略
///
/// 获取字符串长度,中文为两个字符
///
/// 测试的字符串
///
public int GetStrLen(string str)
{
String pattern = @" [^\x00-\xff] " ;
string s = Regex.Replace(str, pattern, " aa " );
return s.Length;
}
///
/// 替换html代码为控件中可见字符
///
///
///
public string DecBrSql(string str)
{
if (str != null && str != "" )
{
str = str.Replace(" " , " " );
str = str.Replace(" " , " " );
}
return str;
}
#region 根据指定字符串长度获取字符串
///
/// 根据指定字符串长度获取字符串
///
/// 要截取的字符串
/// 字符串长度
///
public string GetStrLen(string s, int len)
{
string ss = DecBrSql(s);
int l = GetStrLen(ss);
int i = l / 2 ;
int m = l % 2 ;
if (i > len || (i == len && m > 0 ))
{
return ss.Substring(0 , len) + " .. " ;
}
else
{
return ss;
}
}
#endregion
#endregion
#region 去掉最后一个逗号
///
/// 去掉最后一个逗号
///
///
///
public string DelLastComma(string origin)
{
if (origin.IndexOf(" , " ) == -1 )
{
return origin;
}
if (origin.LastIndexOf(" , " ) + 1 == origin.Length)
{
return origin.Substring(0 , origin.LastIndexOf(" , " ));
}
else
{
return origin;
}
}
public string DelIndexComma(string origin)
{
if (origin.IndexOf(" , " ) == -1 )
{
return origin;
}
if (origin.IndexOf(" , " ) == 0 )
{
return origin.Substring(1 , origin.Length - 1 );
}
else
{
return origin;
}
}
public string DelLastCommad(string origin)
{
if (origin.IndexOf(" . " ) == -1 )
{
return origin;
}
return origin.Substring(0 , origin.LastIndexOf(" . " ));
}
#endregion
#region 替换html代码为控件中可见字符
public string DecSql(string str)
{
if (str != null && str != "" )
{
str = str.Replace(" " , " " );
str = str.Replace(" " , " \r\n " );
}
return str;
}
#endregion
#region 获取拆分符右边的字符串
public string RightSplit(string sourceString, char splitChar)
{
string result = null ;
string [] tempString = sourceString.Split(splitChar);
if (tempString.Length > 0 )
{
result = tempString[tempString.Length - 1 ].ToString();
}
return result;
}
#endregion
#region 转拼音
/**/
///
/// 该类提供将指定汉字转化为拼音码、拼音首字母等一些相关方法;
/// 如果给定的字符为非中文汉字将不执行转化,直接返回原字符;
///
// 编码定义#region 编码定义
private static int [] pyvalue = new int []
{
-20319 , -20317 , -20304 , -20295 , -20292 , -20283 , -20265 , -20257 , -20242 , -20230 , -20051 , -20036 , -20032 ,
-20026 ,
-20002 , -19990 , -19986 , -19982 , -19976 , -19805 , -19784 , -19775 , -19774 , -19763 , -19756 , -19751 , -19746 ,
-19741 , -19739 , -19728 ,
-19725 , -19715 , -19540 , -19531 , -19525 , -19515 , -19500 , -19484 , -19479 , -19467 , -19289 , -19288 , -19281 ,
-19275 , -19270 , -19263 ,
-19261 , -19249 , -19243 , -19242 , -19238 , -19235 , -19227 , -19224 , -19218 , -19212 , -19038 , -19023 , -19018 ,
-19006 , -19003 , -18996 ,
-18977 , -18961 , -18952 , -18783 , -18774 , -18773 , -18763 , -18756 , -18741 , -18735 , -18731 , -18722 , -18710 ,
-18697 , -18696 , -18526 ,
-18518 , -18501 , -18490 , -18478 , -18463 , -18448 , -18447 , -18446 , -18239 , -18237 , -18231 , -18220 , -18211 ,
-18201 , -18184 , -18183 ,
-18181 , -18012 , -17997 , -17988 , -17970 , -17964 , -17961 , -17950 , -17947 , -17931 , -17928 , -17922 , -17759 ,
-17752 , -17733 , -17730 ,
-17721 , -17703 , -17701 , -17697 , -17692 , -17683 , -17676 , -17496 , -17487 , -17482 , -17468 , -17454 , -17433 ,
-17427 , -17417 , -17202 ,
-17185 , -16983 , -16970 , -16942 , -16915 , -16733 , -16708 , -16706 , -16689 , -16664 , -16657 , -16647 , -16474 ,
-16470 , -16465 , -16459 ,
-16452 , -16448 , -16433 , -16429 , -16427 , -16423 , -16419 , -16412 , -16407 , -16403 , -16401 , -16393 , -16220 ,
-16216 , -16212 , -16205 ,
-16202 , -16187 , -16180 , -16171 , -16169 , -16158 , -16155 , -15959 , -15958 , -15944 , -15933 , -15920 , -15915 ,
-15903 , -15889 , -15878 ,
-15707 , -15701 , -15681 , -15667 , -15661 , -15659 , -15652 , -15640 , -15631 , -15625 , -15454 , -15448 , -15436 ,
-15435 , -15419 , -15416 ,
-15408 , -15394 , -15385 , -15377 , -15375 , -15369 , -15363 , -15362 , -15183 , -15180 , -15165 , -15158 , -15153 ,
-15150 , -15149 , -15144 ,
-15143 , -15141 , -15140 , -15139 , -15128 , -15121 , -15119 , -15117 , -15110 , -15109 , -14941 , -14937 , -14933 ,
-14930 , -14929 , -14928 ,
-14926 , -14922 , -14921 , -14914 , -14908 , -14902 , -14894 , -14889 , -14882 , -14873 , -14871 , -14857 , -14678 ,
-14674 , -14670 , -14668 ,
-14663 , -14654 , -14645 , -14630 , -14594 , -14429 , -14407 , -14399 , -14384 , -14379 , -14368 , -14355 , -14353 ,
-14345 , -14170 , -14159 ,
-14151 , -14149 , -14145 , -14140 , -14137 , -14135 , -14125 , -14123 , -14122 , -14112 , -14109 , -14099 , -14097 ,
-14094 , -14092 , -14090 ,
-14087 , -14083 , -13917 , -13914 , -13910 , -13907 , -13906 , -13905 , -13896 , -13894 , -13878 , -13870 , -13859 ,
-13847 , -13831 , -13658 ,
-13611 , -13601 , -13406 , -13404 , -13400 , -13398 , -13395 , -13391 , -13387 , -13383 , -13367 , -13359 , -13356 ,
-13343 , -13340 , -13329 ,
-13326 , -13318 , -13147 , -13138 , -13120 , -13107 , -13096 , -13095 , -13091 , -13076 , -13068 , -13063 , -13060 ,
-12888 , -12875 , -12871 ,
-12860 , -12858 , -12852 , -12849 , -12838 , -12831 , -12829 , -12812 , -12802 , -12607 , -12597 , -12594 , -12585 ,
-12556 , -12359 , -12346 ,
-12320 , -12300 , -12120 , -12099 , -12089 , -12074 , -12067 , -12058 , -12039 , -11867 , -11861 , -11847 , -11831 ,
-11798 , -11781 , -11604 ,
-11589 , -11536 , -11358 , -11340 , -11339 , -11324 , -11303 , -11097 , -11077 , -11067 , -11055 , -11052 , -11045 ,
-11041 , -11038 , -11024 ,
-11020 , -11019 , -11018 , -11014 , -10838 , -10832 , -10815 , -10800 , -10790 , -10780 , -10764 , -10587 , -10544 ,
-10533 , -10519 , -10331 ,
-10329 , -10328 , -10322 , -10315 , -10309 , -10307 , -10296 , -10281 , -10274 , -10270 , -10262 , -10260 , -10256 ,
-10254
};
private static string [] pystr = new string []
{
" a " , " ai " , " an " , " ang " , " ao " , " ba " , " bai " , " ban " , " bang " , " bao " , " bei " , " ben " , " beng " , " bi " , " bian " ,
" biao " ,
" bie " , " bin " , " bing " , " bo " , " bu " , " ca " , " cai " , " can " , " cang " , " cao " , " ce " , " ceng " , " cha " , " chai " , " chan "
, " chang " , " chao " , " che " , " chen " ,
" cheng " , " chi " , " chong " , " chou " , " chu " , " chuai " , " chuan " , " chuang " , " chui " , " chun " , " chuo " , " ci " , " cong "
, " cou " , " cu " , " cuan " , " cui " ,
" cun " , " cuo " , " da " , " dai " , " dan " , " dang " , " dao " , " de " , " deng " , " di " , " dian " , " diao " , " die " , " ding " ,
" diu " , " dong " , " dou " , " du " , " duan " ,
" dui " , " dun " , " duo " , " e " , " en " , " er " , " fa " , " fan " , " fang " , " fei " , " fen " , " feng " , " fo " , " fou " , " fu " , " ga "
, " gai " , " gan " , " gang " , " gao " ,
" ge " , " gei " , " gen " , " geng " , " gong " , " gou " , " gu " , " gua " , " guai " , " guan " , " guang " , " gui " , " gun " , " guo " ,
" ha " , " hai " , " han " , " hang " ,
" hao " , " he " , " hei " , " hen " , " heng " , " hong " , " hou " , " hu " , " hua " , " huai " , " huan " , " huang " , " hui " , " hun " ,
" huo " , " ji " , " jia " , " jian " ,
" jiang " , " jiao " , " jie " , " jin " , " jing " , " jiong " , " jiu " , " ju " , " juan " , " jue " , " jun " , " ka " , " kai " , " kan " ,
" kang " , " kao " , " ke " , " ken " ,
" keng " , " kong " , " kou " , " ku " , " kua " , " kuai " , " kuan " , " kuang " , " kui " , " kun " , " kuo " , " la " , " lai " , " lan " ,
" lang " , " lao " , " le " , " lei " ,
" leng " , " li " , " lia " , " lian " , " liang " , " liao " , " lie " , " lin " , " ling " , " liu " , " long " , " lou " , " lu " , " lv " ,
" luan " , " lue " , " lun " , " luo " ,
" ma " , " mai " , " man " , " mang " , " mao " , " me " , " mei " , " men " , " meng " , " mi " , " mian " , " miao " , " mie " , " min " ,
" ming " , " miu " , " mo " , " mou " , " mu " ,
" na " , " nai " , " nan " , " nang " , " nao " , " ne " , " nei " , " nen " , " neng " , " ni " , " nian " , " niang " , " niao " , " nie " ,
" nin " , " ning " , " niu " , " nong " ,
" nu " , " nv " , " nuan " , " nue " , " nuo " , " o " , " ou " , " pa " , " pai " , " pan " , " pang " , " pao " , " pei " , " pen " , " peng " ,
" pi " , " pian " , " piao " , " pie " ,
" pin " , " ping " , " po " , " pu " , " qi " , " qia " , " qian " , " qiang " , " qiao " , " qie " , " qin " , " qing " , " qiong " , " qiu " ,
" qu " , " quan " , " que " , " qun " ,
" ran " , " rang " , " rao " , " re " , " ren " , " reng " , " ri " , " rong " , " rou " , " ru " , " ruan " , " rui " , " run " , " ruo " , " sa " ,
" sai " , " san " , " sang " ,
" sao " , " se " , " sen " , " seng " , " sha " , " shai " , " shan " , " shang " , " shao " , " she " , " shen " , " sheng " , " shi " ,
" shou " , " shu " , " shua " ,
" shuai " , " shuan " , " shuang " , " shui " , " shun " , " shuo " , " si " , " song " , " sou " , " su " , " suan " , " sui " , " sun " ,
" suo " , " ta " , " tai " ,
" tan " , " tang " , " tao " , " te " , " teng " , " ti " , " tian " , " tiao " , " tie " , " ting " , " tong " , " tou " , " tu " , " tuan " ,
" tui " , " tun " , " tuo " ,
" wa " , " wai " , " wan " , " wang " , " wei " , " wen " , " weng " , " wo " , " wu " , " xi " , " xia " , " xian " , " xiang " , " xiao " ,
" xie " , " xin " , " xing " ,
" xiong " , " xiu " , " xu " , " xuan " , " xue " , " xun " , " ya " , " yan " , " yang " , " yao " , " ye " , " yi " , " yin " , " ying " , " yo " ,
" yong " , " you " ,
" yu " , " yuan " , " yue " , " yun " , " za " , " zai " , " zan " , " zang " , " zao " , " ze " , " zei " , " zen " , " zeng " , " zha " , " zhai "
, " zhan " , " zhang " ,
" zhao " , " zhe " , " zhen " , " zheng " , " zhi " , " zhong " , " zhou " , " zhu " , " zhua " , " zhuai " , " zhuan " , " zhuang " ,
" zhui " , " zhun " , " zhuo " ,
" zi " , " zong " , " zou " , " zu " , " zuan " , " zui " , " zun " , " zuo "
};
// #endregion
/**/
///
/// 将一串中文转化为拼音
/// 如果给定的字符为非中文汉字将不执行转化,直接返回原字符;
///
/// 指定汉字
/// 拼音码
public string ChsString2Spell(string chsstr)
{
string strRet = string .Empty;
char [] ArrChar = chsstr.ToCharArray();
foreach (char c in ArrChar)
{
strRet += SingleChs2Spell(c.ToString());
}
return strRet;
}
/**/
///
/// 将一串中文转化为拼音
///
/// 指定汉字
/// 拼音首字母
public string GetHeadOfChs(string chsstr)
{
string strRet = string .Empty;
char [] ArrChar = chsstr.ToCharArray();
foreach (char c in ArrChar)
{
strRet += GetHeadOfSingleChs(c.ToString());
}
return strRet;
}
/**/
///
/// 单个汉字转化为拼音
///
/// 单个汉字
/// 拼音
public string SingleChs2Spell(string SingleChs)
{
byte [] array;
int iAsc;
string strRtn = string .Empty;
array = Encoding.Default.GetBytes(SingleChs);
try
{
iAsc = (short )(array[0 ]) * 256 + (short )(array[1 ]) - 65536 ;
}
catch
{
iAsc = 1 ;
}
if (iAsc > 0 && iAsc < 160 )
return SingleChs;
for (int i = (pyvalue.Length - 1 ); i >= 0 ; i--)
{
if (pyvalue[i] <= iAsc)
{
strRtn = pystr[i];
break ;
}
}
// 将首字母转为大写
if (strRtn.Length > 1 )
{
strRtn = strRtn.Substring(0 , 1 ).ToUpper() + strRtn.Substring(1 );
}
return strRtn;
}
/**/
///
/// 得到单个汉字拼音的首字母
///
///
public string GetHeadOfSingleChs(string SingleChs)
{
return SingleChs2Spell(SingleChs).Substring(0 , 1 );
}
#endregion
#region CheckBoxList取值及绑定
public string GetCheckBoxList(CheckBoxList CheckBoxList1)
{
string cblist = "" ;
for (int i = 0 ; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected == true )
{
if (cblist == "" )
{
cblist += CheckBoxList1.Items[i].Value;
}
else
{
cblist += " , " + CheckBoxList1.Items[i].Value;
}
}
}
return cblist;
}
public string GetCheckBoxListTxt(CheckBoxList CheckBoxList1)
{
string cblist = "" ;
for (int i = 0 ; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected == true )
{
if (cblist == "" )
{
cblist += CheckBoxList1.Items[i].Text;
}
else
{
cblist += " , " + CheckBoxList1.Items[i].Text;
}
}
}
return cblist;
}
public void PutCheckBoxList(CheckBoxList CheckBoxList1, string value)
{
string [] strTemp = value.Split(' , ' );
foreach (string str in strTemp)
{
for (int i = 0 ; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Value == str)
{
CheckBoxList1.Items[i].Selected = true ;
}
}
}
}
#endregion
#region 下载
public void DownFile(System.Web.UI.Page page, string filename)
{
if (filename != "" )
{
string path = page.Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
page.Response.Clear();
page.Response.AddHeader( " Content-Disposition " , " attachment; filename= " + file.Name);
page.Response.AddHeader( " Content-Length " , file.Length.ToString());
page.Response.ContentType = " application/octet-stream " ;
page.Response.Filter.Close();
page.Response.WriteFile(file.FullName);
page.Response.End();
}
else
{
ResponseScript(page, " alert('文件不存在!');window.close(); " );
}
}
}
#endregion
public string GetClientFullPathName(System.Web.UI.Page page, string file)
{
string FullPathName = "" ;
WebbUpload m_upload = new WebbUpload();
UploadFile m_file = m_upload.GetUploadFile(file);
FullPathName = m_file.ClientFullPathName;
return FullPathName;
}
#endregion
public object SubStringByByte(string p)
{
throw new NotImplementedException();
}
}
}