Web关于图片上传,缩略图及加水印,还有一些常用的方法

[csharp]  view plain  copy
  1. /// <summary>  
  2.         /// 裁剪图片并保存  
  3.         /// </summary>  
  4.         public bool cropSaveAs(string fileName, string newFileName, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y)  
  5.         {  
  6.             string fileExt = Utils.GetFileExt(fileName); //文件扩展名,不含“.”  
  7.             if (!IsImage(fileExt))  
  8.             {  
  9.                 return false;  
  10.             }  
  11.             string newFileDir = Utils.GetMapPath(newFileName.Substring(0, newFileName.LastIndexOf(@"/") + 1));  
  12.             //检查是否有该路径,没有则创建  
  13.             if (!Directory.Exists(newFileDir))  
  14.             {  
  15.                 Directory.CreateDirectory(newFileDir);  
  16.             }  
  17.             try  
  18.             {  
  19.                 string fileFullPath = Utils.GetMapPath(fileName);  
  20.                 string toFileFullPath = Utils.GetMapPath(newFileName);  
  21.                 return Thumbnail.MakeThumbnailImage(fileFullPath, toFileFullPath, 180, 180, cropWidth, cropHeight, X, Y);  
  22.             }  
  23.             catch  
  24.             {  
  25.                 return false;  
  26.             }  
  27.         }  
  28.   
  29.         /// <summary>  
  30.         /// 文件上传方法  
  31.         /// </summary>  
  32.         /// <param name="postedFile">文件流</param>  
  33.         /// <param name="isThumbnail">是否生成缩略图</param>  
  34.         /// <param name="isWater">是否打水印</param>  
  35.         /// <returns>上传后文件信息</returns>  
  36.         public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater)  
  37.         {  
  38.             try  
  39.             {  
  40.                 string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.”  
  41.                 int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位  
  42.                 string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名  
  43.                 string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名  
  44.                 string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名  
  45.                 string upLoadPath = GetUpLoadPath(); //上传目录相对路径  
  46.                 string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径  
  47.                 string newFilePath = upLoadPath + newFileName; //上传后的路径  
  48.                 string newThumbnailPath = upLoadPath + newThumbnailFileName; //上传后的缩略图路径  
  49.   
  50.                 //检查文件扩展名是否合法  
  51.                 if (!CheckFileExt(fileExt))  
  52.                 {  
  53.                     return "{\"status\": 0, \"msg\": \"不允许上传" + fileExt + "类型的文件!\"}";  
  54.                 }  
  55.                 //检查文件大小是否合法  
  56.                 if (!CheckFileSize(fileExt, fileSize))  
  57.                 {  
  58.                     return "{\"status\": 0, \"msg\": \"文件超过限制的大小!\"}";  
  59.                 }  
  60.                 //检查上传的物理路径是否存在,不存在则创建  
  61.                 if (!Directory.Exists(fullUpLoadPath))  
  62.                 {  
  63.                     Directory.CreateDirectory(fullUpLoadPath);  
  64.                 }  
  65.   
  66.                 //保存文件  
  67.                 postedFile.SaveAs(fullUpLoadPath + newFileName);  
  68.                 //如果是图片,检查图片是否超出最大尺寸,是则裁剪  
  69.                 if (IsImage(fileExt) && (this.siteConfig.imgmaxheight > 0 || this.siteConfig.imgmaxwidth > 0))  
  70.                 {  
  71.                     Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newFileName,  
  72.                         this.siteConfig.imgmaxwidth, this.siteConfig.imgmaxheight);  
  73.                 }  
  74.                 //如果是图片,检查是否需要生成缩略图,是则生成  
  75.                 if (IsImage(fileExt) && isThumbnail && this.siteConfig.thumbnailwidth > 0 && this.siteConfig.thumbnailheight > 0)  
  76.                 {  
  77.                     Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName,  
  78.                         this.siteConfig.thumbnailwidth, this.siteConfig.thumbnailheight, "Cut");  
  79.                 }  
  80.                 else  
  81.                 {  
  82.                     newThumbnailPath = newFilePath; //不生成缩略图则返回原图  
  83.                 }  
  84.                 //如果是图片,检查是否需要打水印  
  85.                 if (IsWaterMark(fileExt) && isWater)  
  86.                 {  
  87.                     switch (this.siteConfig.watermarktype)  
  88.                     {  
  89.                         case 1:  
  90.                             WaterMark.AddImageSignText(newFilePath, newFilePath,  
  91.                                 this.siteConfig.watermarktext, this.siteConfig.watermarkposition,  
  92.                                 this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize);  
  93.                             break;  
  94.                         case 2:  
  95.                             WaterMark.AddImageSignPic(newFilePath, newFilePath,  
  96.                                 this.siteConfig.watermarkpic, this.siteConfig.watermarkposition,  
  97.                                 this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency);  
  98.                             break;  
  99.                     }  
  100.                 }  
  101.                 //处理完毕,返回JOSN格式的文件信息  
  102.                 return "{\"status\": 1, \"msg\": \"上传文件成功!\", \"name\": \""  
  103.                     + fileName + "\", \"path\": \"" + newFilePath + "\", \"thumb\": \""  
  104.                     + newThumbnailPath + "\", \"size\": " + fileSize + ", \"ext\": \"" + fileExt + "\"}";  
  105.             }  
  106.             catch  
  107.             {  
  108.                 return "{\"status\": 0, \"msg\": \"上传过程中发生意外错误!\"}";  
  109.             }  
  110.         }  
  111.   
  112.         /// <summary>  
  113.         /// 保存远程文件到本地  
  114.         /// </summary>  
  115.         /// <param name="fileUri">URI地址</param>  
  116.         /// <returns>上传后的路径</returns>  
  117.         public string remoteSaveAs(string fileUri)  
  118.         {  
  119.             WebClient client = new WebClient();  
  120.             string fileExt = string.Empty; //文件扩展名,不含“.”  
  121.             if (fileUri.LastIndexOf(".") == -1)  
  122.             {  
  123.                 fileExt = "gif";  
  124.             }  
  125.             else  
  126.             {  
  127.                 fileExt = Utils.GetFileExt(fileUri);  
  128.             }  
  129.             string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名  
  130.             string upLoadPath = GetUpLoadPath(); //上传目录相对路径  
  131.             string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径  
  132.             string newFilePath = upLoadPath + newFileName; //上传后的路径  
  133.             //检查上传的物理路径是否存在,不存在则创建  
  134.             if (!Directory.Exists(fullUpLoadPath))  
  135.             {  
  136.                 Directory.CreateDirectory(fullUpLoadPath);  
  137.             }  
  138.   
  139.             try  
  140.             {  
  141.                 client.DownloadFile(fileUri, fullUpLoadPath + newFileName);  
  142.                 //如果是图片,检查是否需要打水印  
  143.                 if (IsWaterMark(fileExt))  
  144.                 {  
  145.                     switch (this.siteConfig.watermarktype)  
  146.                     {  
  147.                         case 1:  
  148.                             WaterMark.AddImageSignText(newFilePath, newFilePath,  
  149.                                 this.siteConfig.watermarktext, this.siteConfig.watermarkposition,  
  150.                                 this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize);  
  151.                             break;  
  152.                         case 2:  
  153.                             WaterMark.AddImageSignPic(newFilePath, newFilePath,  
  154.                                 this.siteConfig.watermarkpic, this.siteConfig.watermarkposition,  
  155.                                 this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency);  
  156.                             break;  
  157.                     }  
  158.                 }  
  159.             }  
  160.             catch  
  161.             {  
  162.                 return string.Empty;  
  163.             }  
  164.             client.Dispose();  
  165.             return newFilePath;  
  166.         }  
  167.  
  168.         #region 私有方法  
  169.         /// <summary>  
  170.         /// 返回上传目录相对路径  
  171.         /// </summary>  
  172.         /// <param name="fileName">上传文件名</param>  
  173.         private string GetUpLoadPath()  
  174.         {  
  175.             string path = siteConfig.webpath + siteConfig.filepath + "/"//站点目录+上传目录  
  176.             switch (this.siteConfig.filesave)  
  177.             {  
  178.                 case 1: //按年月日每天一个文件夹  
  179.                     path += DateTime.Now.ToString("yyyyMMdd");  
  180.                     break;  
  181.                 default//按年月/日存入不同的文件夹  
  182.                     path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");  
  183.                     break;  
  184.             }  
  185.             return path + "/";  
  186.         }  
  187.   
  188.         /// <summary>  
  189.         /// 是否需要打水印  
  190.         /// </summary>  
  191.         /// <param name="_fileExt">文件扩展名,不含“.”</param>  
  192.         private bool IsWaterMark(string _fileExt)  
  193.         {  
  194.             //判断是否开启水印  
  195.             if (this.siteConfig.watermarktype > 0)  
  196.             {  
  197.                 //判断是否可以打水印的图片类型  
  198.                 ArrayList al = new ArrayList();  
  199.                 al.Add("bmp");  
  200.                 al.Add("jpeg");  
  201.                 al.Add("jpg");  
  202.                 al.Add("png");  
  203.                 if (al.Contains(_fileExt.ToLower()))  
  204.                 {  
  205.                     return true;  
  206.                 }  
  207.             }  
  208.             return false;  
  209.         }  
  210.   
  211.         /// <summary>  
  212.         /// 是否为图片文件  
  213.         /// </summary>  
  214.         /// <param name="_fileExt">文件扩展名,不含“.”</param>  
  215.         private bool IsImage(string _fileExt)  
  216.         {  
  217.             ArrayList al = new ArrayList();  
  218.             al.Add("bmp");  
  219.             al.Add("jpeg");  
  220.             al.Add("jpg");  
  221.             al.Add("gif");  
  222.             al.Add("png");  
  223.             if (al.Contains(_fileExt.ToLower()))  
  224.             {  
  225.                 return true;  
  226.             }  
  227.             return false;  
  228.         }  
  229.   
  230.         /// <summary>  
  231.         /// 检查是否为合法的上传文件  
  232.         /// </summary>  
  233.         private bool CheckFileExt(string _fileExt)  
  234.         {  
  235.             //检查危险文件  
  236.             string[] excExt = { "asp""aspx""ashx""asa""asmx""asax""php""jsp""htm""html" };  
  237.             for (int i = 0; i < excExt.Length; i++)  
  238.             {  
  239.                 if (excExt[i].ToLower() == _fileExt.ToLower())  
  240.                 {  
  241.                     return false;  
  242.                 }  
  243.             }  
  244.             //检查合法文件  
  245.             string[] allowExt = (this.siteConfig.fileextension + "," + this.siteConfig.videoextension).Split(',');  
  246.             for (int i = 0; i < allowExt.Length; i++)  
  247.             {  
  248.                 if (allowExt[i].ToLower() == _fileExt.ToLower())  
  249.                 {  
  250.                     return true;  
  251.                 }  
  252.             }  
  253.             return false;  
  254.         }  
  255.   
  256.         /// <summary>  
  257.         /// 检查文件大小是否合法  
  258.         /// </summary>  
  259.         /// <param name="_fileExt">文件扩展名,不含“.”</param>  
  260.         /// <param name="_fileSize">文件大小(B)</param>  
  261.         private bool CheckFileSize(string _fileExt, int _fileSize)  
  262.         {  
  263.             //将视频扩展名转换成ArrayList  
  264.             ArrayList lsVideoExt = new ArrayList(this.siteConfig.videoextension.ToLower().Split(','));  
  265.             //判断是否为图片文件  
  266.             if (IsImage(_fileExt))  
  267.             {  
  268.                 if (this.siteConfig.imgsize > 0 && _fileSize > this.siteConfig.imgsize * 1024)  
  269.                 {  
  270.                     return false;  
  271.                 }  
  272.             }  
  273.             else if (lsVideoExt.Contains(_fileExt.ToLower()))  
  274.             {  
  275.                 if (this.siteConfig.videosize > 0 && _fileSize > this.siteConfig.videosize * 1024)  
  276.                 {  
  277.                     return false;  
  278.                 }  
  279.             }  
  280.             else  
  281.             {  
  282.                 if (this.siteConfig.attachsize > 0 && _fileSize > this.siteConfig.attachsize * 1024)  
  283.                 {  
  284.                     return false;  
  285.                 }  
  286.             }  
  287.             return true;  
  288.         }  
  289.         #endregion  






[csharp]  view plain  copy
  1. public class Utils  
  2.     {  
  3.         #region 系统版本  
  4.         /// <summary>  
  5.         /// 版本信息类  
  6.         /// </summary>  
  7.         public class VersionInfo  
  8.         {  
  9.             public int FileMajorPart  
  10.             {  
  11.                 get { return 4; }  
  12.             }  
  13.             public int FileMinorPart  
  14.             {  
  15.                 get { return 0; }  
  16.             }  
  17.             public int FileBuildPart  
  18.             {  
  19.                 get { return 0; }  
  20.             }  
  21.             public string ProductName  
  22.             {  
  23.                 get { return "DTcms"; }  
  24.             }  
  25.             public int ProductType  
  26.             {  
  27.                 get { return 1; }  
  28.             }  
  29.         }  
  30.         public static string GetVersion()  
  31.         {  
  32.             return DTKeys.ASSEMBLY_VERSION;  
  33.         }  
  34.         #endregion  
  35.  
  36.         #region MD5加密  
  37.         public static string MD5(string pwd)  
  38.         {  
  39.             MD5 md5 = new MD5CryptoServiceProvider();  
  40.             byte[] data = System.Text.Encoding.Default.GetBytes(pwd);  
  41.             byte[] md5data = md5.ComputeHash(data);  
  42.             md5.Clear();  
  43.             string str = "";  
  44.             for (int i = 0; i < md5data.Length; i++)  
  45.             {  
  46.                 str += md5data[i].ToString("x").PadLeft(2, '0');  
  47.   
  48.             }  
  49.             return str;  
  50.         }  
  51.         #endregion  
  52.  
  53.         #region 对象转换处理  
  54.         /// <summary>  
  55.         /// 判断对象是否为Int32类型的数字  
  56.         /// </summary>  
  57.         /// <param name="Expression"></param>  
  58.         /// <returns></returns>  
  59.         public static bool IsNumeric(object expression)  
  60.         {  
  61.             if (expression != null)  
  62.                 return IsNumeric(expression.ToString());  
  63.   
  64.             return false;  
  65.   
  66.         }  
  67.   
  68.         /// <summary>  
  69.         /// 判断对象是否为Int32类型的数字  
  70.         /// </summary>  
  71.         /// <param name="Expression"></param>  
  72.         /// <returns></returns>  
  73.         public static bool IsNumeric(string expression)  
  74.         {  
  75.             if (expression != null)  
  76.             {  
  77.                 string str = expression;  
  78.                 if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))  
  79.                 {  
  80.                     if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))  
  81.                         return true;  
  82.                 }  
  83.             }  
  84.             return false;  
  85.         }  
  86.         /// <summary>  
  87.         /// 截取字符串长度,超出部分使用后缀suffix代替,比如abcdevfddd取前3位,后面使用...代替  
  88.         /// </summary>  
  89.         /// <param name="orginStr"></param>  
  90.         /// <param name="length"></param>  
  91.         /// <param name="suffix"></param>  
  92.         /// <returns></returns>  
  93.         public static string SubStrAddSuffix(string orginStr, int length, string suffix)  
  94.         {  
  95.             string ret = orginStr;  
  96.             if (orginStr.Length > length)  
  97.             {  
  98.                 ret = orginStr.Substring(0, length) + suffix;  
  99.             }  
  100.             return ret;  
  101.         }  
  102.         /// <summary>  
  103.         /// 是否为Double类型  
  104.         /// </summary>  
  105.         /// <param name="expression"></param>  
  106.         /// <returns></returns>  
  107.         public static bool IsDouble(object expression)  
  108.         {  
  109.             if (expression != null)  
  110.                 return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");  
  111.   
  112.             return false;  
  113.         }  
  114.   
  115.         /// <summary>  
  116.         /// 检测是否符合email格式  
  117.         /// </summary>  
  118.         /// <param name="strEmail">要判断的email字符串</param>  
  119.         /// <returns>判断结果</returns>  
  120.         public static bool IsValidEmail(string strEmail)  
  121.         {  
  122.             return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");  
  123.         }  
  124.         public static bool IsValidDoEmail(string strEmail)  
  125.         {  
  126.             return Regex.IsMatch(strEmail, @"^@((
    [09]1,3\.[09]1,3\.[09]1,3\.)|(([\w]+\.)+))([azAZ]2,4|[09]1,3)(
    ?)$");  
  127.         }  
  128.   
  129.         /// <summary>  
  130.         /// 检测是否是正确的Url  
  131.         /// </summary>  
  132.         /// <param name="strUrl">要验证的Url</param>  
  133.         /// <returns>判断结果</returns>  
  134.         public static bool IsURL(string strUrl)  
  135.         {  
  136.             return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");  
  137.         }  
  138.   
  139.         /// <summary>  
  140.         /// 将字符串转换为数组  
  141.         /// </summary>  
  142.         /// <param name="str">字符串</param>  
  143.         /// <returns>字符串数组</returns>  
  144.         public static string[] GetStrArray(string str)  
  145.         {  
  146.             return str.Split(new char[',']);  
  147.         }  
  148.   
  149.         /// <summary>  
  150.         /// 将数组转换为字符串  
  151.         /// </summary>  
  152.         /// <param name="list">List</param>  
  153.         /// <param name="speater">分隔符</param>  
  154.         /// <returns>String</returns>  
  155.         public static string GetArrayStr(List<string> list, string speater)  
  156.         {  
  157.             StringBuilder sb = new StringBuilder();  
  158.             for (int i = 0; i < list.Count; i++)  
  159.             {  
  160.                 if (i == list.Count - 1)  
  161.                 {  
  162.                     sb.Append(list[i]);  
  163.                 }  
  164.                 else  
  165.                 {  
  166.                     sb.Append(list[i]);  
  167.                     sb.Append(speater);  
  168.                 }  
  169.             }  
  170.             return sb.ToString();  
  171.         }  
  172.   
  173.         /// <summary>  
  174.         /// object型转换为bool型  
  175.         /// </summary>  
  176.         /// <param name="strValue">要转换的字符串</param>  
  177.         /// <param name="defValue">缺省值</param>  
  178.         /// <returns>转换后的bool类型结果</returns>  
  179.         public static bool StrToBool(object expression, bool defValue)  
  180.         {  
  181.             if (expression != null)  
  182.                 return StrToBool(expression, defValue);  
  183.   
  184.             return defValue;  
  185.         }  
  186.   
  187.         /// <summary>  
  188.         /// string型转换为bool型  
  189.         /// </summary>  
  190.         /// <param name="strValue">要转换的字符串</param>  
  191.         /// <param name="defValue">缺省值</param>  
  192.         /// <returns>转换后的bool类型结果</returns>  
  193.         public static bool StrToBool(string expression, bool defValue)  
  194.         {  
  195.             if (expression != null)  
  196.             {  
  197.                 if (string.Compare(expression, "true"true) == 0)  
  198.                     return true;  
  199.                 else if (string.Compare(expression, "false"true) == 0)  
  200.                     return false;  
  201.             }  
  202.             return defValue;  
  203.         }  
  204.   
  205.         /// <summary>  
  206.         /// 将对象转换为Int32类型  
  207.         /// </summary>  
  208.         /// <param name="expression">要转换的字符串</param>  
  209.         /// <param name="defValue">缺省值</param>  
  210.         /// <returns>转换后的int类型结果</returns>  
  211.         public static int ObjToInt(object expression, int defValue)  
  212.         {  
  213.             if (expression != null)  
  214.                 return StrToInt(expression.ToString(), defValue);  
  215.   
  216.             return defValue;  
  217.         }  
  218.   
  219.         /// <summary>  
  220.         /// 将字符串转换为Int32类型  
  221.         /// </summary>  
  222.         /// <param name="expression">要转换的字符串</param>  
  223.         /// <param name="defValue">缺省值</param>  
  224.         /// <returns>转换后的int类型结果</returns>  
  225.         public static int StrToInt(string expression, int defValue)  
  226.         {  
  227.             if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex.IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))  
  228.                 return defValue;  
  229.   
  230.             int rv;  
  231.             if (Int32.TryParse(expression, out rv))  
  232.                 return rv;  
  233.   
  234.             return Convert.ToInt32(StrToFloat(expression, defValue));  
  235.         }  
  236.   
  237.         /// <summary>  
  238.         /// Object型转换为decimal型  
  239.         /// </summary>  
  240.         /// <param name="strValue">要转换的字符串</param>  
  241.         /// <param name="defValue">缺省值</param>  
  242.         /// <returns>转换后的decimal类型结果</returns>  
  243.         public static decimal ObjToDecimal(object expression, decimal defValue)  
  244.         {  
  245.             if (expression != null)  
  246.                 return StrToDecimal(expression.ToString(), defValue);  
  247.   
  248.             return defValue;  
  249.         }  
  250.   
  251.         /// <summary>  
  252.         /// string型转换为decimal型  
  253.         /// </summary>  
  254.         /// <param name="strValue">要转换的字符串</param>  
  255.         /// <param name="defValue">缺省值</param>  
  256.         /// <returns>转换后的decimal类型结果</returns>  
  257.         public static decimal StrToDecimal(string expression, decimal defValue)  
  258.         {  
  259.             if ((expression == null) || (expression.Length > 10))  
  260.                 return defValue;  
  261.   
  262.             decimal intValue = defValue;  
  263.             if (expression != null)  
  264.             {  
  265.                 bool IsDecimal = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");  
  266.                 if (IsDecimal)  
  267.                     decimal.TryParse(expression, out intValue);  
  268.             }  
  269.             return intValue;  
  270.         }  
  271.   
  272.         /// <summary>  
  273.         /// Object型转换为float型  
  274.         /// </summary>  
  275.         /// <param name="strValue">要转换的字符串</param>  
  276.         /// <param name="defValue">缺省值</param>  
  277.         /// <returns>转换后的int类型结果</returns>  
  278.         public static float ObjToFloat(object expression, float defValue)  
  279.         {  
  280.             if (expression != null)  
  281.                 return StrToFloat(expression.ToString(), defValue);  
  282.   
  283.             return defValue;  
  284.         }  
  285.   
  286.         /// <summary>  
  287.         /// string型转换为float型  
  288.         /// </summary>  
  289.         /// <param name="strValue">要转换的字符串</param>  
  290.         /// <param name="defValue">缺省值</param>  
  291.         /// <returns>转换后的int类型结果</returns>  
  292.         public static float StrToFloat(string expression, float defValue)  
  293.         {  
  294.             if ((expression == null) || (expression.Length > 10))  
  295.                 return defValue;  
  296.   
  297.             float intValue = defValue;  
  298.             if (expression != null)  
  299.             {  
  300.                 bool IsFloat = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");  
  301.                 if (IsFloat)  
  302.                     float.TryParse(expression, out intValue);  
  303.             }  
  304.             return intValue;  
  305.         }  
  306.   
  307.         /// <summary>  
  308.         /// 将对象转换为日期时间类型  
  309.         /// </summary>  
  310.         /// <param name="str">要转换的字符串</param>  
  311.         /// <param name="defValue">缺省值</param>  
  312.         /// <returns>转换后的int类型结果</returns>  
  313.         public static DateTime StrToDateTime(string str, DateTime defValue)  
  314.         {  
  315.             if (!string.IsNullOrEmpty(str))  
  316.             {  
  317.                 DateTime dateTime;  
  318.                 if (DateTime.TryParse(str, out dateTime))  
  319.                     return dateTime;  
  320.             }  
  321.             return defValue;  
  322.         }  
  323.   
  324.         /// <summary>  
  325.         /// 将对象转换为日期时间类型  
  326.         /// </summary>  
  327.         /// <param name="str">要转换的字符串</param>  
  328.         /// <returns>转换后的int类型结果</returns>  
  329.         public static DateTime StrToDateTime(string str)  
  330.         {  
  331.             return StrToDateTime(str, DateTime.Now);  
  332.         }  
  333.   
  334.         /// <summary>  
  335.         /// 将对象转换为日期时间类型  
  336.         /// </summary>  
  337.         /// <param name="obj">要转换的对象</param>  
  338.         /// <returns>转换后的int类型结果</returns>  
  339.         public static DateTime ObjectToDateTime(object obj)  
  340.         {  
  341.             return StrToDateTime(obj.ToString());  
  342.         }  
  343.   
  344.         /// <summary>  
  345.         /// 将对象转换为日期时间类型  
  346.         /// </summary>  
  347.         /// <param name="obj">要转换的对象</param>  
  348.         /// <param name="defValue">缺省值</param>  
  349.         /// <returns>转换后的int类型结果</returns>  
  350.         public static DateTime ObjectToDateTime(object obj, DateTime defValue)  
  351.         {  
  352.             return StrToDateTime(obj.ToString(), defValue);  
  353.         }  
  354.   
  355.         /// <summary>  
  356.         /// 将对象转换为字符串  
  357.         /// </summary>  
  358.         /// <param name="obj">要转换的对象</param>  
  359.         /// <returns>转换后的string类型结果</returns>  
  360.         public static string ObjectToStr(object obj)  
  361.         {  
  362.             if (obj == null)  
  363.                 return "";  
  364.             return obj.ToString().Trim();  
  365.         }  
  366.   
  367.         /// <summary>  
  368.         /// 将对象转换为Int类型  
  369.         /// </summary>  
  370.         /// <param name="o"></param>  
  371.         /// <returns></returns>  
  372.         public static int ObjToInt(object obj)  
  373.         {  
  374.             if (isNumber(obj))  
  375.             {  
  376.                 return int.Parse(obj.ToString());  
  377.             }  
  378.             else  
  379.             {  
  380.                 return 0;  
  381.             }  
  382.         }  
  383.         /// <summary>  
  384.         /// 判断对象是否可以转成int型  
  385.         /// </summary>  
  386.         /// <param name="o"></param>  
  387.         /// <returns></returns>  
  388.         public static bool isNumber(object o)  
  389.         {  
  390.             int tmpInt;  
  391.             if (o == null)  
  392.             {  
  393.                 return false;  
  394.             }  
  395.             if (o.ToString().Trim().Length == 0)  
  396.             {  
  397.                 return false;  
  398.             }  
  399.             if (!int.TryParse(o.ToString(), out tmpInt))  
  400.             {  
  401.                 return false;  
  402.             }  
  403.             else  
  404.             {  
  405.                 return true;  
  406.             }  
  407.         }  
  408.         #endregion  
  409.  
  410.         #region 分割字符串  
  411.         /// <summary>  
  412.         /// 分割字符串  
  413.         /// </summary>  
  414.         public static string[] SplitString(string strContent, string strSplit)  
  415.         {  
  416.             if (!string.IsNullOrEmpty(strContent))  
  417.             {  
  418.                 if (strContent.IndexOf(strSplit) < 0)  
  419.                     return new string[] { strContent };  
  420.   
  421.                 return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);  
  422.             }  
  423.             else  
  424.                 return new string[0] { };  
  425.         }  
  426.   
  427.         /// <summary>  
  428.         /// 分割字符串  
  429.         /// </summary>  
  430.         /// <returns></returns>  
  431.         public static string[] SplitString(string strContent, string strSplit, int count)  
  432.         {  
  433.             string[] result = new string[count];  
  434.             string[] splited = SplitString(strContent, strSplit);  
  435.   
  436.             for (int i = 0; i < count; i++)  
  437.             {  
  438.                 if (i < splited.Length)  
  439.                     result[i] = splited[i];  
  440.                 else  
  441.                     result[i] = string.Empty;  
  442.             }  
  443.   
  444.             return result;  
  445.         }  
  446.         #endregion  
  447.  
  448.         #region 删除最后结尾的一个逗号  
  449.         /// <summary>  
  450.         /// 删除最后结尾的一个逗号  
  451.         /// </summary>  
  452.         public static string DelLastComma(string str)  
  453.         {  
  454.             if (str.Length < 1)  
  455.             {  
  456.                 return "";  
  457.             }  
  458.             return str.Substring(0, str.LastIndexOf(","));  
  459.         }  
  460.         #endregion  
  461.  
  462.         #region 删除最后结尾的指定字符后的字符  
  463.         /// <summary>  
  464.         /// 删除最后结尾的指定字符后的字符  
  465.         /// </summary>  
  466.         public static string DelLastChar(string str, string strchar)  
  467.         {  
  468.             if (string.IsNullOrEmpty(str))  
  469.                 return "";  
  470.             if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)  
  471.             {  
  472.                 return str.Substring(0, str.LastIndexOf(strchar));  
  473.             }  
  474.             return str;  
  475.         }  
  476.         #endregion  
  477.  
  478.         #region 生成指定长度的字符串  
  479.         /// <summary>  
  480.         /// 生成指定长度的字符串,即生成strLong个str字符串  
  481.         /// </summary>  
  482.         /// <param name="strLong">生成的长度</param>  
  483.         /// <param name="str">以str生成字符串</param>  
  484.         /// <returns></returns>  
  485.         public static string StringOfChar(int strLong, string str)  
  486.         {  
  487.             string ReturnStr = "";  
  488.             for (int i = 0; i < strLong; i++)  
  489.             {  
  490.                 ReturnStr += str;  
  491.             }  
  492.   
  493.             return ReturnStr;  
  494.         }  
  495.         #endregion  
  496.  
  497.         #region 生成日期随机码  
  498.         /// <summary>  
  499.         /// 生成日期随机码  
  500.         /// </summary>  
  501.         /// <returns></returns>  
  502.         public static string GetRamCode()  
  503.         {  
  504.             #region  
  505.             return DateTime.Now.ToString("yyyyMMddHHmmssffff");  
  506.             #endregion  
  507.         }  
  508.         #endregion  
  509.  
  510.         #region 生成随机字母或数字  
  511.         /// <summary>  
  512.         /// 生成随机数字  
  513.         /// </summary>  
  514.         /// <param name="length">生成长度</param>  
  515.         /// <returns></returns>  
  516.         public static string Number(int Length)  
  517.         {  
  518.             return Number(Length, false);  
  519.         }  
  520.   
  521.         /// <summary>  
  522.         /// 生成随机数字  
  523.         /// </summary>  
  524.         /// <param name="Length">生成长度</param>  
  525.         /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>  
  526.         /// <returns></returns>  
  527.         public static string Number(int Length, bool Sleep)  
  528.         {  
  529.             if (Sleep)  
  530.                 System.Threading.Thread.Sleep(3);  
  531.             string result = "";  
  532.             System.Random random = new Random();  
  533.             for (int i = 0; i < Length; i++)  
  534.             {  
  535.                 result += random.Next(10).ToString();  
  536.             }  
  537.             return result;  
  538.         }  
  539.         /// <summary>  
  540.         /// 生成随机字母字符串(数字字母混和)  
  541.         /// </summary>  
  542.         /// <param name="codeCount">待生成的位数</param>  
  543.         public static string GetCheckCode(int codeCount)  
  544.         {  
  545.             string str = string.Empty;  
  546.             int rep = 0;  
  547.             long num2 = DateTime.Now.Ticks + rep;  
  548.             rep++;  
  549.             Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));  
  550.             for (int i = 0; i < codeCount; i++)  
  551.             {  
  552.                 char ch;  
  553.                 int num = random.Next();  
  554.                 if ((num % 2) == 0)  
  555.                 {  
  556.                     ch = (char)(0x30 + ((ushort)(num % 10)));  
  557.                 }  
  558.                 else  
  559.                 {  
  560.                     ch = (char)(0x41 + ((ushort)(num % 0x1a)));  
  561.                 }  
  562.                 str = str + ch.ToString();  
  563.             }  
  564.             return str;  
  565.         }  
  566.         /// <summary>  
  567.         /// 根据日期和随机码生成订单号  
  568.         /// </summary>  
  569.         /// <returns></returns>  
  570.         public static string GetOrderNumber()  
  571.         {  
  572.             string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms  
  573.             return num + Number(2, true).ToString();  
  574.         }  
  575.         private static int Next(int numSeeds, int length)  
  576.         {  
  577.             byte[] buffer = new byte[length];  
  578.             System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();  
  579.             Gen.GetBytes(buffer);  
  580.             uint randomResult = 0x0;//这里用uint作为生成的随机数    
  581.             for (int i = 0; i < length; i++)  
  582.             {  
  583.                 randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));  
  584.             }  
  585.             return (int)(randomResult % numSeeds);  
  586.         }  
  587.         #endregion  
  588.  
  589.         #region 截取字符长度  
  590.         /// <summary>  
  591.         /// 截取字符长度  
  592.         /// </summary>  
  593.         /// <param name="inputString">字符</param>  
  594.         /// <param name="len">长度</param>  
  595.         /// <returns></returns>  
  596.         public static string CutString(string inputString, int len)  
  597.         {  
  598.             if (string.IsNullOrEmpty(inputString))  
  599.                 return "";  
  600.             inputString = DropHTML(inputString);  
  601.             ASCIIEncoding ascii = new ASCIIEncoding();  
  602.             int tempLen = 0;  
  603.             string tempString = "";  
  604.             byte[] s = ascii.GetBytes(inputString);  
  605.             for (int i = 0; i < s.Length; i++)  
  606.             {  
  607.                 if ((int)s[i] == 63)  
  608.                 {  
  609.                     tempLen += 2;  
  610.                 }  
  611.                 else  
  612.                 {  
  613.                     tempLen += 1;  
  614.                 }  
  615.   
  616.                 try  
  617.                 {  
  618.                     tempString += inputString.Substring(i, 1);  
  619.                 }  
  620.                 catch  
  621.                 {  
  622.                     break;  
  623.                 }  
  624.   
  625.                 if (tempLen > len)  
  626.                     break;  
  627.             }  
  628.             //如果截过则加上半个省略号   
  629.             byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);  
  630.             if (mybyte.Length > len)  
  631.                 tempString += "…";  
  632.             return tempString;  
  633.         }  
  634.         #endregion  
  635.  
  636.         #region 清除HTML标记  
  637.         public static string DropHTML(string Htmlstring)  
  638.         {  
  639.             if (string.IsNullOrEmpty(Htmlstring)) return "";  
  640.             //删除脚本    
  641.             Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>""", RegexOptions.IgnoreCase);  
  642.             //删除HTML    
  643.             Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>""", RegexOptions.IgnoreCase);  
  644.             Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+""", RegexOptions.IgnoreCase);  
  645.             Htmlstring = Regex.Replace(Htmlstring, @"-->""", RegexOptions.IgnoreCase);  
  646.             Htmlstring = Regex.Replace(Htmlstring, @"<!--.*""", RegexOptions.IgnoreCase);  
  647.             Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);""\"", RegexOptions.IgnoreCase);  
  648.             Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);""&", RegexOptions.IgnoreCase);  
  649.             Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);""<", RegexOptions.IgnoreCase);  
  650.             Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);"">", RegexOptions.IgnoreCase);  
  651.             Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);"" ", RegexOptions.IgnoreCase);  
  652.             Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);""\xa1", RegexOptions.IgnoreCase);  
  653.             Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);""\xa2", RegexOptions.IgnoreCase);  
  654.             Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);""\xa3", RegexOptions.IgnoreCase);  
  655.             Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);""\xa9", RegexOptions.IgnoreCase);  
  656.   
  657.             Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);""", RegexOptions.IgnoreCase);  
  658.             Htmlstring.Replace("<""");  
  659.             Htmlstring.Replace(">""");  
  660.             Htmlstring.Replace("\r\n""");  
  661.             Htmlstring.Replace(" """);  
  662.             Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();  
  663.             return Htmlstring;  
  664.         }  
  665.         #endregion  
  666.  
  667.         #region 清除HTML标记且返回相应的长度  
  668.         public static string DropHTML(string Htmlstring, int strLen)  
  669.         {  
  670.             return CutString(DropHTML(Htmlstring), strLen);  
  671.         }  
  672.         #endregion  
  673.  
  674.         #region TXT代码转换成HTML格式  
  675.         /// <summary>  
  676.         /// 字符串字符处理  
  677.         /// </summary>  
  678.         /// <param name="chr">等待处理的字符串</param>  
  679.         /// <returns>处理后的字符串</returns>  
  680.         /// //把TXT代码转换成HTML格式  
  681.         public static String ToHtml(string Input)  
  682.         {  
  683.             StringBuilder sb = new StringBuilder(Input);  
  684.             sb.Replace("&""&");  
  685.             sb.Replace("<""<");  
  686.             sb.Replace(">"">");  
  687.             sb.Replace("\r\n""<br />");  
  688.             sb.Replace("\n""<br />");  
  689.             sb.Replace("\t"" ");  
  690.             //sb.Replace(" ", " ");  
  691.             return sb.ToString();  
  692.         }  
  693.         #endregion  
  694.  
  695.         #region HTML代码转换成TXT格式  
  696.         /// <summary>  
  697.         /// 字符串字符处理  
  698.         /// </summary>  
  699.         /// <param name="chr">等待处理的字符串</param>  
  700.         /// <returns>处理后的字符串</returns>  
  701.         /// //把HTML代码转换成TXT格式  
  702.         public static String ToTxt(String Input)  
  703.         {  
  704.             StringBuilder sb = new StringBuilder(Input);  
  705.             sb.Replace(" "" ");  
  706.             sb.Replace("<br>""\r\n");  
  707.             sb.Replace("<br>""\n");  
  708.             sb.Replace("<br />""\n");  
  709.             sb.Replace("<br />""\r\n");  
  710.             sb.Replace("<""<");  
  711.             sb.Replace(">"">");  
  712.             sb.Replace("&""&");  
  713.             return sb.ToString();  
  714.         }  
  715.         #endregion  
  716.  
  717.         #region 检测是否有Sql危险字符  
  718.         /// <summary>  
  719.         /// 检测是否有Sql危险字符  
  720.         /// </summary>  
  721.         /// <param name="str">要判断字符串</param>  
  722.         /// <returns>判断结果</returns>  
  723.         public static bool IsSafeSqlString(string str)  
  724.         {  
  725.             return !Regex.IsMatch(str, @"[-|;|,|\/| | |
    |
    |\}|\{|%|@|\*|!|\']");  
  726.         }  
  727.           
  728.         /// <summary>  
  729.         /// 检查危险字符  
  730.         /// </summary>  
  731.         /// <param name="Input"></param>  
  732.         /// <returns></returns>  
  733.         public static string Filter(string sInput)  
  734.         {  
  735.             if (sInput == null || sInput == "")  
  736.                 return null;  
  737.             string sInput1 = sInput.ToLower();  
  738.             string output = sInput;  
  739.             string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";  
  740.             if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)  
  741.             {  
  742.                 throw new Exception("字符串中含有非法字符!");  
  743.             }  
  744.             else  
  745.             {  
  746.                 output = output.Replace("'""''");  
  747.             }  
  748.             return output;  
  749.         }  
  750.   
  751.         /// <summary>   
  752.         /// 检查过滤设定的危险字符  
  753.         /// </summary>   
  754.         /// <param name="InText">要过滤的字符串 </param>   
  755.         /// <returns>如果参数存在不安全字符,则返回true </returns>   
  756.         public static bool SqlFilter(string word, string InText)  
  757.         {  
  758.             if (InText == null)  
  759.                 return false;  
  760.             foreach (string i in word.Split('|'))  
  761.             {  
  762.                 if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))  
  763.                 {  
  764.                     return true;  
  765.                 }  
  766.             }  
  767.             return false;  
  768.         }  
  769.         #endregion  
  770.  
  771.         #region 过滤特殊字符  
  772.         /// <summary>  
  773.         /// 过滤特殊字符  
  774.         /// </summary>  
  775.         /// <param name="Input"></param>  
  776.         /// <returns></returns>  
  777.         public static string Htmls(string Input)  
  778.         {  
  779.             if (Input != string.Empty && Input != null)  
  780.             {  
  781.                 string ihtml = Input.ToLower();  
  782.                 ihtml = ihtml.Replace("<script""<script");  
  783.                 ihtml = ihtml.Replace("script>""script>");  
  784.                 ihtml = ihtml.Replace("<%""<%");  
  785.                 ihtml = ihtml.Replace("%>""%>");  
  786.                 ihtml = ihtml.Replace("<$""<$");  
  787.                 ihtml = ihtml.Replace("$>""$>");  
  788.                 return ihtml;  
  789.             }  
  790.             else  
  791.             {  
  792.                 return string.Empty;  
  793.             }  
  794.         }  
  795.         #endregion  
  796.  
  797.         #region 检查是否为IP地址  
  798.         /// <summary>  
  799.         /// 是否为ip  
  800.         /// </summary>  
  801.         /// <param name="ip"></param>  
  802.         /// <returns></returns>  
  803.         public static bool IsIP(string ip)  
  804.         {  
  805.             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?)$");  
  806.         }  
  807.         #endregion  
  808.  
  809.         #region 获得配置文件节点XML文件的绝对路径  
  810.         public static string GetXmlMapPath(string xmlName)  
  811.         {  
  812.             return GetMapPath(ConfigurationManager.AppSettings[xmlName].ToString());  
  813.         }  
  814.         #endregion  
  815.  
  816.         #region 获得当前绝对路径  
  817.         /// <summary>  
  818.         /// 获得当前绝对路径  
  819.         /// </summary>  
  820.         /// <param name="strPath">指定的路径</param>  
  821.         /// <returns>绝对路径</returns>  
  822.         public static string GetMapPath(string strPath)  
  823.         {  
  824.             if (strPath.ToLower().StartsWith("http://"))  
  825.             {  
  826.                 return strPath;  
  827.             }  
  828.             if (HttpContext.Current != null)  
  829.             {  
  830.                 return HttpContext.Current.Server.MapPath(strPath);  
  831.             }  
  832.             else //非web程序引用  
  833.             {  
  834.                 strPath = strPath.Replace("/""\\");  
  835.                 if (strPath.StartsWith("\\"))  
  836.                 {  
  837.                     strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');  
  838.                 }  
  839.                 return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);  
  840.             }  
  841.         }  
  842.         #endregion  
  843.  
  844.         #region 文件操作  
  845.         /// <summary>  
  846.         /// 删除单个文件  
  847.         /// </summary>  
  848.         /// <param name="_filepath">文件相对路径</param>  
  849.         public static bool DeleteFile(string _filepath)  
  850.         {  
  851.             if (string.IsNullOrEmpty(_filepath))  
  852.             {  
  853.                 return false;  
  854.             }  
  855.             string fullpath = GetMapPath(_filepath);  
  856.             if (File.Exists(fullpath))  
  857.             {  
  858.                 File.Delete(fullpath);  
  859.                 return true;  
  860.             }  
  861.             return false;  
  862.         }  
  863.   
  864.         /// <summary>  
  865.         /// 删除上传的文件(及缩略图)  
  866.         /// </summary>  
  867.         /// <param name="_filepath"></param>  
  868.         public static void DeleteUpFile(string _filepath)  
  869.         {  
  870.             if (string.IsNullOrEmpty(_filepath))  
  871.             {  
  872.                 return;  
  873.             }  
  874.             string fullpath = GetMapPath(_filepath); //原图  
  875.             if (File.Exists(fullpath))  
  876.             {  
  877.                 File.Delete(fullpath);  
  878.             }  
  879.             if (_filepath.LastIndexOf("/") >= 0)  
  880.             {  
  881.                 string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);  
  882.                 string fullTPATH = GetMapPath(thumbnailpath); //宿略图  
  883.                 if (File.Exists(fullTPATH))  
  884.                 {  
  885.                     File.Delete(fullTPATH);  
  886.                 }  
  887.             }  
  888.         }  
  889.   
  890.         /// <summary>  
  891.         /// 删除内容图片  
  892.         /// </summary>  
  893.         /// <param name="content">内容</param>  
  894.         /// <param name="startstr">匹配开头字符串</param>  
  895.         public static void DeleteContentPic(string content, string startstr)  
  896.         {  
  897.             if (string.IsNullOrEmpty(content))  
  898.             {  
  899.                 return;  
  900.             }  
  901.             Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);  
  902.             MatchCollection m = reg.Matches(content);  
  903.             foreach (Match math in m)  
  904.             {  
  905.                 string imgUrl = math.Groups[1].Value;  
  906.                 string fullPath = GetMapPath(imgUrl);  
  907.                 try  
  908.                 {  
  909.                     if (imgUrl.ToLower().StartsWith(startstr.ToLower()) && File.Exists(fullPath))  
  910.                     {  
  911.                         File.Delete(fullPath);  
  912.                     }  
  913.                 }  
  914.                 catch { }  
  915.             }  
  916.         }  
  917.   
  918.         /// <summary>  
  919.         /// 删除指定文件夹  
  920.         /// </summary>  
  921.         /// <param name="_dirpath">文件相对路径</param>  
  922.         public static bool DeleteDirectory(string _dirpath)  
  923.         {  
  924.             if (string.IsNullOrEmpty(_dirpath))  
  925.             {  
  926.                 return false;  
  927.             }  
  928.             string fullpath = GetMapPath(_dirpath);  
  929.             if (Directory.Exists(fullpath))  
  930.             {  
  931.                 Directory.Delete(fullpath, true);  
  932.                 return true;  
  933.             }  
  934.             return false;  
  935.         }  
  936.   
  937.         /// <summary>  
  938.         /// 修改指定文件夹名称  
  939.         /// </summary>  
  940.         /// <param name="old_dirpath">旧相对路径</param>  
  941.         /// <param name="new_dirpath">新相对路径</param>  
  942.         /// <returns>bool</returns>  
  943.         public static bool MoveDirectory(string old_dirpath, string new_dirpath)  
  944.         {  
  945.             if (string.IsNullOrEmpty(old_dirpath))  
  946.             {  
  947.                 return false;  
  948.             }  
  949.             string fulloldpath = GetMapPath(old_dirpath);  
  950.             string fullnewpath = GetMapPath(new_dirpath);  
  951.             if (Directory.Exists(fulloldpath))  
  952.             {  
  953.                 Directory.Move(fulloldpath, fullnewpath);  
  954.                 return true;  
  955.             }  
  956.             return false;  
  957.         }  
  958.   
  959.         /// <summary>  
  960.         /// 返回文件大小KB  
  961.         /// </summary>  
  962.         /// <param name="_filepath">文件相对路径</param>  
  963.         /// <returns>int</returns>  
  964.         public static int GetFileSize(string _filepath)  
  965.         {  
  966.             if (string.IsNullOrEmpty(_filepath))  
  967.             {  
  968.                 return 0;  
  969.             }  
  970.             string fullpath = GetMapPath(_filepath);  
  971.             if (File.Exists(fullpath))  
  972.             {  
  973.                 FileInfo fileInfo = new FileInfo(fullpath);  
  974.                 return ((int)fileInfo.Length) / 1024;  
  975.             }  
  976.             return 0;  
  977.         }  
  978.   
  979.         /// <summary>  
  980.         /// 返回文件扩展名,不含“.”  
  981.         /// </summary>  
  982.         /// <param name="_filepath">文件全名称</param>  
  983.         /// <returns>string</returns>  
  984.         public static string GetFileExt(string _filepath)  
  985.         {  
  986.             if (string.IsNullOrEmpty(_filepath))  
  987.             {  
  988.                 return "";  
  989.             }  
  990.             if (_filepath.LastIndexOf(".") > 0)  
  991.             {  
  992.                 return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”  
  993.             }  
  994.             return "";  
  995.         }  
  996.   
  997.         /// <summary>  
  998.         /// 返回文件名,不含路径  
  999.         /// </summary>  
  1000.         /// <param name="_filepath">文件相对路径</param>  
  1001.         /// <returns>string</returns>  
  1002.         public static string GetFileName(string _filepath)  
  1003.         {  
  1004.             return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1);  
  1005.         }  
  1006.   
  1007.         /// <summary>  
  1008.         /// 文件是否存在  
  1009.         /// </summary>  
  1010.         /// <param name="_filepath">文件相对路径</param>  
  1011.         /// <returns>bool</returns>  
  1012.         public static bool FileExists(string _filepath)  
  1013.         {  
  1014.             string fullpath = GetMapPath(_filepath);  
  1015.             if (File.Exists(fullpath))  
  1016.             {  
  1017.                 return true;  
  1018.             }  
  1019.             return false;  
  1020.         }  
  1021.   
  1022.         /// <summary>  
  1023.         /// 获得远程字符串  
  1024.         /// </summary>  
  1025.         public static string GetDomainStr(string key, string uriPath)  
  1026.         {  
  1027.             string result = CacheHelper.Get(key) as string;  
  1028.             if (result == null)  
  1029.             {  
  1030.                 System.Net.WebClient client = new System.Net.WebClient();  
  1031.                 try  
  1032.                 {  
  1033.                     client.Encoding = System.Text.Encoding.UTF8;  
  1034.                     result = client.DownloadString(uriPath);  
  1035.                 }  
  1036.                 catch  
  1037.                 {  
  1038.                     result = "暂时无法连接!";  
  1039.                 }  
  1040.                 CacheHelper.Insert(key, result, 60);  
  1041.             }  
  1042.   
  1043.             return result;  
  1044.         }  
  1045.  
  1046.         #endregion  
  1047.  
  1048.         #region 读取或写入cookie  
  1049.         /// <summary>  
  1050.         /// 写cookie值  
  1051.         /// </summary>  
  1052.         /// <param name="strName">名称</param>  
  1053.         /// <param name="strValue">值</param>  
  1054.         public static void WriteCookie(string strName, string strValue)  
  1055.         {  
  1056.             HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];  
  1057.             if (cookie == null)  
  1058.             {  
  1059.                 cookie = new HttpCookie(strName);  
  1060.             }  
  1061.             cookie.Value = UrlEncode(strValue);  
  1062.             HttpContext.Current.Response.AppendCookie(cookie);  
  1063.         }  
  1064.   
  1065.         /// <summary>  
  1066.         /// 写cookie值  
  1067.         /// </summary>  
  1068.         /// <param name="strName">名称</param>  
  1069.         /// <param name="strValue">值</param>  
  1070.         public static void WriteCookie(string strName, string key, string strValue)  
  1071.         {  
  1072.             HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];  
  1073.             if (cookie == null)  
  1074.             {  
  1075.                 cookie = new HttpCookie(strName);  
  1076.             }  
  1077.             cookie[key] = UrlEncode(strValue);  
  1078.             HttpContext.Current.Response.AppendCookie(cookie);  
  1079.         }  
  1080.   
  1081.         /// <summary>  
  1082.         /// 写cookie值  
  1083.         /// </summary>  
  1084.         /// <param name="strName">名称</param>  
  1085.         /// <param name="strValue">值</param>  
  1086.         public static void WriteCookie(string strName, string key, string strValue, int expires)  
  1087.         {  
  1088.             HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];  
  1089.             if (cookie == null)  
  1090.             {  
  1091.                 cookie = new HttpCookie(strName);  
  1092.             }  
  1093.             cookie[key] = UrlEncode(strValue);  
  1094.             cookie.Expires = DateTime.Now.AddMinutes(expires);  
  1095.             HttpContext.Current.Response.AppendCookie(cookie);  
  1096.         }  
  1097.   
  1098.         /// <summary>  
  1099.         /// 写cookie值  
  1100.         /// </summary>  
  1101.         /// <param name="strName">名称</param>  
  1102.         /// <param name="strValue">值</param>  
  1103.         /// <param name="strValue">过期时间(分钟)</param>  
  1104.         public static void WriteCookie(string strName, string strValue, int expires)  
  1105.         {  
  1106.             HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];  
  1107.             if (cookie == null)  
  1108.             {  
  1109.                 cookie = new HttpCookie(strName);  
  1110.             }  
  1111.             cookie.Value = UrlEncode(strValue);  
  1112.             cookie.Expires = DateTime.Now.AddMinutes(expires);  
  1113.             HttpContext.Current.Response.AppendCookie(cookie);  
  1114.         }  
  1115.   
  1116.         /// <summary>  
  1117.         /// 读cookie值  
  1118.         /// </summary>  
  1119.         /// <param name="strName">名称</param>  
  1120.         /// <returns>cookie值</returns>  
  1121.         public static string GetCookie(string strName)  
  1122.         {  
  1123.             if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)  
  1124.                 return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());  
  1125.             return "";  
  1126.         }  
  1127.   
  1128.         /// <summary>  
  1129.         /// 读cookie值  
  1130.         /// </summary>  
  1131.         /// <param name="strName">名称</param>  
  1132.         /// <returns>cookie值</returns>  
  1133.         public static string GetCookie(string strName, string key)  
  1134.         {  
  1135.             if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)  
  1136.                 return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());  
  1137.   
  1138.             return "";  
  1139.         }  
  1140.         #endregion  
  1141.  
  1142.         #region 替换指定的字符串  
  1143.         /// <summary>  
  1144.         /// 替换指定的字符串  
  1145.         /// </summary>  
  1146.         /// <param name="originalStr">原字符串</param>  
  1147.         /// <param name="oldStr">旧字符串</param>  
  1148.         /// <param name="newStr">新字符串</param>  
  1149.         /// <returns></returns>  
  1150.         public static string ReplaceStr(string originalStr, string oldStr, string newStr)  
  1151.         {  
  1152.             if (string.IsNullOrEmpty(oldStr))  
  1153.             {  
  1154.                 return "";  
  1155.             }  
  1156.             return originalStr.Replace(oldStr, newStr);  
  1157.         }  
  1158.         #endregion  
  1159.  
  1160.         #region 显示分页  
  1161.         /// <summary>  
  1162.         /// 返回分页页码  
  1163.         /// </summary>  
  1164.         /// <param name="pageSize">页面大小</param>  
  1165.         /// <param name="pageIndex">当前页</param>  
  1166.         /// <param name="totalCount">总记录数</param>  
  1167.         /// <param name="linkUrl">链接地址,__id__代表页码</param>  
  1168.         /// <param name="centSize">中间页码数量</param>  
  1169.         /// <returns></returns>  
  1170.         public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize)  
  1171.         {  
  1172.             //计算页数  
  1173.             if (totalCount < 1 || pageSize < 1)  
  1174.             {  
  1175.                 return "";  
  1176.             }  
  1177.             int pageCount = totalCount / pageSize;  
  1178.             if (pageCount < 1)  
  1179.             {  
  1180.                 return "";  
  1181.             }  
  1182.             if (totalCount % pageSize > 0)  
  1183.             {  
  1184.                 pageCount += 1;  
  1185.             }  
  1186.             if (pageCount <= 1)  
  1187.             {  
  1188.                 return "";  
  1189.             }  
  1190.             StringBuilder pageStr = new StringBuilder();  
  1191.             string pageId = "__id__";  
  1192.             string firstBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">«上一页</a>";  
  1193.             string lastBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一页»</a>";  
  1194.             string firstStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, "1") + "\">1</a>";  
  1195.             string lastStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, pageCount.ToString()) + "\">" + pageCount.ToString() + "</a>";  
  1196.   
  1197.             if (pageIndex <= 1)  
  1198.             {  
  1199.                 firstBtn = "<span class=\"disabled\">«上一页</span>";  
  1200.             }  
  1201.             if (pageIndex >= pageCount)  
  1202.             {  
  1203.                 lastBtn = "<span class=\"disabled\">下一页»</span>";  
  1204.             }  
  1205.             if (pageIndex == 1)  
  1206.             {  
  1207.                 firstStr = "<span class=\"current\">1</span>";  
  1208.             }  
  1209.             if (pageIndex == pageCount)  
  1210.             {  
  1211.                 lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>";  
  1212.             }  
  1213.             int firstNum = pageIndex - (centSize / 2); //中间开始的页码  
  1214.             if (pageIndex < centSize)  
  1215.                 firstNum = 2;  
  1216.             int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //中间结束的页码  
  1217.             if (lastNum >= pageCount)  
  1218.                 lastNum = pageCount - 1;  
  1219.             pageStr.Append("<span>共" + totalCount + "记录</span>");  
  1220.             pageStr.Append(firstBtn + firstStr);  
  1221.             if (pageIndex >= centSize)  
  1222.             {  
  1223.                 pageStr.Append("<span>...</span>\n");  
  1224.             }  
  1225.             for (int i = firstNum; i <= lastNum; i++)  
  1226.             {  
  1227.                 if (i == pageIndex)  
  1228.                 {  
  1229.                     pageStr.Append("<span class=\"current\">" + i + "</span>");  
  1230.                 }  
  1231.                 else  
  1232.                 {  
  1233.                     pageStr.Append("<a href=\"" + ReplaceStr(linkUrl, pageId, i.ToString()) + "\">" + i + "</a>");  
  1234.                 }  
  1235.             }  
  1236.             if (pageCount - pageIndex > centSize - ((centSize / 2)))  
  1237.             {  
  1238.                 pageStr.Append("<span>...</span>");  
  1239.             }  
  1240.             pageStr.Append(lastStr + lastBtn);  
  1241.             return pageStr.ToString();  
  1242.         }  
  1243.         #endregion  
  1244.  
  1245.         #region URL处理  
  1246.         /// <summary>  
  1247.         /// URL字符编码  
  1248.         /// </summary>  
  1249.         public static string UrlEncode(string str)  
  1250.         {  
  1251.             if (string.IsNullOrEmpty(str))  
  1252.             {  
  1253.                 return "";  
  1254.             }  
  1255.             str = str.Replace("'""");  
  1256.             return HttpContext.Current.Server.UrlEncode(str);  
  1257.         }  
  1258.   
  1259.         /// <summary>  
  1260.         /// URL字符解码  
  1261.         /// </summary>  
  1262.         public static string UrlDecode(string str)  
  1263.         {  
  1264.             if (string.IsNullOrEmpty(str))  
  1265.             {  
  1266.                 return "";  
  1267.             }  
  1268.             return HttpContext.Current.Server.UrlDecode(str);  
  1269.         }  
  1270.   
  1271.         /// <summary>  
  1272.         /// 组合URL参数  
  1273.         /// </summary>  
  1274.         /// <param name="_url">页面地址</param>  
  1275.         /// <param name="_keys">参数名称</param>  
  1276.         /// <param name="_values">参数值</param>  
  1277.         /// <returns>String</returns>  
  1278.         public static string CombUrlTxt(string _url, string _keys, params string[] _values)  
  1279.         {  
  1280.             StringBuilder urlParams = new StringBuilder();  
  1281.             try  
  1282.             {  
  1283.                 string[] keyArr = _keys.Split(new char[] { '&' });  
  1284.                 for (int i = 0; i < keyArr.Length; i++)  
  1285.                 {  
  1286.                     if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")  
  1287.                     {  
  1288.                         _values[i] = UrlEncode(_values[i]);  
  1289.                         urlParams.Append(string.Format(keyArr[i], _values) + "&");  
  1290.                     }  
  1291.                 }  
  1292.                 if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)  
  1293.                     urlParams.Insert(0, "?");  
  1294.             }  
  1295.             catch  
  1296.             {  
  1297.                 return _url;  
  1298.             }  
  1299.             return _url + DelLastChar(urlParams.ToString(), "&");  
  1300.         }  
  1301.         #endregion  
  1302.  
  1303.         #region URL请求数据  
  1304.         /// <summary>  
  1305.         /// HTTP POST方式请求数据  
  1306.         /// </summary>  
  1307.         /// <param name="url">URL.</param>  
  1308.         /// <param name="param">POST的数据</param>  
  1309.         /// <returns></returns>  
  1310.         public static string HttpPost(string url, string param)  
  1311.         {  
  1312.             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);  
  1313.             request.Method = "POST";  
  1314.             request.ContentType = "application/x-www-form-urlencoded";  
  1315.             request.Accept = "*/*";  
  1316.             request.Timeout = 15000;  
  1317.             request.AllowAutoRedirect = false;  
  1318.   
  1319.             StreamWriter requestStream = null;  
  1320.             WebResponse response = null;  
  1321.             string responseStr = null;  
  1322.   
  1323.             try  
  1324.             {  
  1325.                 requestStream = new StreamWriter(request.GetRequestStream());  
  1326.                 requestStream.Write(param);  
  1327.                 requestStream.Close();  
  1328.   
  1329.                 response = request.GetResponse();  
  1330.                 if (response != null)  
  1331.                 {  
  1332.                     StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
  1333.                     responseStr = reader.ReadToEnd();  
  1334.                     reader.Close();  
  1335.                 }  
  1336.             }  
  1337.             catch (Exception)  
  1338.             {  
  1339.                 throw;  
  1340.             }  
  1341.             finally  
  1342.             {  
  1343.                 request = null;  
  1344.                 requestStream = null;  
  1345.                 response = null;  
  1346.             }  
  1347.   
  1348.             return responseStr;  
  1349.         }  
  1350.           
  1351.         /// <summary>  
  1352.         /// HTTP GET方式请求数据.  
  1353.         /// </summary>  
  1354.         /// <param name="url">URL.</param>  
  1355.         /// <returns></returns>  
  1356.         public static string HttpGet(string url)  
  1357.         {  
  1358.             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);  
  1359.             request.Method = "GET";  
  1360.             //request.ContentType = "application/x-www-form-urlencoded";  
  1361.             request.Accept = "*/*";  
  1362.             request.Timeout = 15000;  
  1363.             request.AllowAutoRedirect = false;  
  1364.   
  1365.             WebResponse response = null;  
  1366.             string responseStr = null;  
  1367.   
  1368.             try  
  1369.             {  
  1370.                 response = request.GetResponse();  
  1371.   
  1372.                 if (response != null)  
  1373.                 {  
  1374.                     StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);  
  1375.                     responseStr = reader.ReadToEnd();  
  1376.                     reader.Close();  
  1377.                 }  
  1378.             }  
  1379.             catch (Exception)  
  1380.             {  
  1381.                 throw;  
  1382.             }  
  1383.             finally  
  1384.             {  
  1385.                 request = null;  
  1386.                 response = null;  
  1387.             }  
  1388.   
  1389.             return responseStr;  
  1390.         }  
  1391.   
  1392.         /// <summary>  
  1393.         /// 执行URL获取页面内容  
  1394.         /// </summary>  
  1395.         public static string UrlExecute(string urlPath)  
  1396.         {  
  1397.             if (string.IsNullOrEmpty(urlPath))  
  1398.             {  
  1399.                 return "error";  
  1400.             }  
  1401.             StringWriter sw = new StringWriter();  
  1402.             try  
  1403.             {  
  1404.                 HttpContext.Current.Server.Execute(urlPath, sw);  
  1405.                 return sw.ToString();  
  1406.             }  
  1407.             catch (Exception)  
  1408.             {  
  1409.                 return "error";  
  1410.             }  
  1411.             finally  
  1412.             {  
  1413.                 sw.Close();  
  1414.                 sw.Dispose();  
  1415.             }  
  1416.         }  
  1417.         #endregion  
  1418.  
  1419.         #region 操作权限菜单  
  1420.         /// <summary>  
  1421.         /// 获取操作权限  
  1422.         /// </summary>  
  1423.         /// <returns>Dictionary</returns>  
  1424.         public static Dictionary<stringstring> ActionType()  
  1425.         {  
  1426.             Dictionary<stringstring> dic = new Dictionary<stringstring>();  
  1427.             dic.Add("Show""显示");  
  1428.             dic.Add("View""查看");  
  1429.             dic.Add("Add""添加");  
  1430.             dic.Add("Edit""修改");  
  1431.             dic.Add("Delete""删除");  
  1432.             dic.Add("Audit""审核");  
  1433.             dic.Add("Reply""回复");  
  1434.             dic.Add("Confirm""确认");  
  1435.             dic.Add("Cancel""取消");  
  1436.             dic.Add("Invalid""作废");  
  1437.             dic.Add("Build""生成");  
  1438.             dic.Add("Instal""安装");  
  1439.             dic.Add("Unload""卸载");  
  1440.             dic.Add("Back""备份");  
  1441.             dic.Add("Restore""还原");  
  1442.             dic.Add("Replace""替换");  
  1443.             return dic;  
  1444.         }  
  1445.         #endregion  
  1446.  
  1447.         #region 替换URL  
  1448.         /// <summary>  
  1449.         /// 替换扩展名  
  1450.         /// </summary>  
  1451.         public static string GetUrlExtension(string urlPage, string staticExtension)  
  1452.         {  
  1453.             int indexNum = urlPage.LastIndexOf('.');  
  1454.             if (indexNum > 0)  
  1455.             {  
  1456.                 return urlPage.Replace(urlPage.Substring(indexNum), "." + staticExtension);  
  1457.             }  
  1458.             return urlPage;  
  1459.         }  
  1460.         /// <summary>  
  1461.         /// 替换扩展名,如没有扩展名替换默认首页  
  1462.         /// </summary>  
  1463.         public static string GetUrlExtension(string urlPage, string staticExtension, bool defaultVal)  
  1464.         {  
  1465.             int indexNum = urlPage.LastIndexOf('.');  
  1466.             if (indexNum > 0)  
  1467.             {  
  1468.                 return urlPage.Replace(urlPage.Substring(indexNum), "." + staticExtension);  
  1469.             }  
  1470.             if (defaultVal)  
  1471.             {  
  1472.                 if (urlPage.EndsWith("/"))  
  1473.                 {  
  1474.                     return urlPage + "index." + staticExtension;  
  1475.                 }  
  1476.                 else  
  1477.                 {  
  1478.                     return urlPage + "/index." + staticExtension;  
  1479.                 }  
  1480.             }  
  1481.             return urlPage;  
  1482.         }  
  1483.         #endregion  
  1484.   
  1485.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值