.Net 开发中的一些可参考公用方法 C#

来源:互联网 发布:数据可视化 js 编辑:程序博客网 时间:2024/05/22 02:07
using System;using System.Configuration;using System.Web;using System.Web.UI;using System.Text;using System.Text.RegularExpressions;using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Security.Cryptography;/*一般放在BLL层下的Common.cs文件中:using System;                         //string using System.Configuration;           //调用web.config要引用的命名空间using System.Web;                     //HttpContextusing System.Web.UI;                  //ctl.RenderControl(new HtmlTextWriter(tempWriter));using System.Text;                    //StringBuilderusing System.Text.RegularExpressions; //Regexusing System.Drawing;                 // Image originalImage = Image.FromFile(originalImagePath);using System.IO;                      //TextWriter tempWriter = new StringWriter();using System.Security.Cryptography;   //DESCryptoServiceProvider des = new DESCryptoServiceProvider();*/namespace System{    #region 公用方法    /// <summary>    /// 公用方法    /// </summary>    public class Common    {        public Common()        {            //            // TODO: 在此处添加构造函数逻辑            //        }        #region 1、防止SQL注入方法        /// <summary>        /// 防止SQL注入,过滤字符串        /// </summary>        /// <param name="arg"></param>        /// <returns></returns>        public static string ReplaceSqlStr(string arg)        {            string[] Lawlesses ={ "=", "net user", "xp_cmdshell", "add", "exec master.dbo.xp_cmdshell", "net localgroup administrators", "select", "Asc", "count", "char", "mid", "'", "/"", "insert", "delete from", "drop table", "update", "truncate", "from", "%" };            StringBuilder rltsb = new StringBuilder();            StringBuilder sb = new StringBuilder();            sb.Append(arg);            rltsb.Append(arg);            for (int i = 0; i < Lawlesses.Length; i++)            {                while (sb.ToString().IndexOf(Lawlesses[i], System.StringComparison.CurrentCultureIgnoreCase) >= 0)                {                    rltsb.Remove(0, rltsb.Length);                    rltsb.Append(sb.ToString().Substring(0, sb.ToString().IndexOf(Lawlesses[i], System.StringComparison.CurrentCultureIgnoreCase)) + "*" + sb.ToString().Substring(sb.ToString().IndexOf(Lawlesses[i], System.StringComparison.CurrentCultureIgnoreCase) + Lawlesses[i].Length));                    sb.Remove(0, sb.Length);                    sb.Append(rltsb.ToString());                }            }            return rltsb.ToString();        }        #endregion        #region 2、获取客户端真实IP        /// <summary>         /// 取得客户端真实IP。如果有代理则取第一个非内网地址         /// </summary>         public static string IPAddress        {            get            {                string result = String.Empty;                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];                if (result != null && result != String.Empty)                {                    //可能有代理                     if (result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式                         result = null;                    else                    {                        if (result.IndexOf(",") != -1)                        {                            //有“,”,估计多个代理。取第一个不是内网的IP。                             result = result.Replace(" ", "").Replace("'", "");                            string[] temparyip = result.Split(",;".ToCharArray());                            for (int i = 0; i < temparyip.Length; i++)                            {                                if (IsIPAddress(temparyip[i])                                    && temparyip[i].Substring(0, 3) != "10."                                    && temparyip[i].Substring(0, 7) != "192.168"                                    && temparyip[i].Substring(0, 7) != "172.16.")                                {                                    return temparyip[i];    //找到不是内网的地址                                 }                            }                        }                        else if (IsIPAddress(result)) //代理即是IP格式                             return result;                        else                            result = null;    //代理中的内容 非IP,取IP                     }                }                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];                if (null == result || result == String.Empty)                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];                if (result == null || result == String.Empty)                    result = HttpContext.Current.Request.UserHostAddress;                return result;            }        }        /// <summary>        /// 判断是否是IP地址格式 0.0.0.0        /// </summary>        /// <param name="str1">待判断的IP地址</param>        /// <returns>true or false</returns>        private static bool IsIPAddress(string str1)        {            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;            string regformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}___FCKpd___0quot;;            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);            return regex.IsMatch(str1);        }        #endregion        #region 3、生成缩略图        /// <summary>        /// 生成缩略图        /// </summary>        /// <param name="originalImagePath">源图路径(物理路径)</param>        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>        /// <param name="width">缩略图宽度</param>        /// <param name="height">缩略图高度</param>        /// <param name="mode">生成缩略图的方式--"W"://指定宽,高按比例、"H"://指定高,宽按比例、"HW"://指定高宽,缩放于指定的范围内</param>        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)        {            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);            int towidth = width;            int toheight = height;            int x = 0;            int y = 0;            int ow = originalImage.Width;            int oh = originalImage.Height;            switch (mode)            {                case "HW"://指定高宽缩放(可能变形:2006-5-27樊海斌修改:使显示图片不变形。)                    if (originalImage.Height * 1.0 / originalImage.Width > 1.0)                    {                        towidth = originalImage.Width * width / originalImage.Height;                    }                    else                    {                        toheight = originalImage.Height * height / originalImage.Width;                    }                    break;                case "W"://指定宽,高按比例                    toheight = originalImage.Height * width / originalImage.Width;                    break;                case "H"://指定高,宽按比例                    towidth = originalImage.Width * height / originalImage.Height;                    break;                case "Cut"://指定高宽裁减(不变形)                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)                    {                        oh = originalImage.Height;                        ow = originalImage.Height * towidth / toheight;                        y = 0;                        x = (originalImage.Width - ow) / 2;                    }                    else                    {                        ow = originalImage.Width;                        oh = originalImage.Width * height / towidth;                        x = 0;                        y = (originalImage.Height - oh) / 2;                    }                    break;                default:                    break;            }            //新建一个bmp图片            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);            //新建一个画板            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);            //=========用于旋转图片======樊海斌=======            //Matrix myMatrix = new Matrix();            //PointF pointF00 = new PointF(0,0);             //myMatrix.Rotate(30.6f);            //myMatrix.RotateAt(30.6f,pointF00);   //按指定点旋转            //g.Transform=myMatrix;            //=========================================            //在指定位置并且按指定大小绘制原图片的指定部分            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);            try            {                //以jpg格式保存缩略图                bitmap.Save(thumbnailPath, originalImage.RawFormat);            }            catch (System.Exception e)            {                throw e;            }            finally            {                originalImage.Dispose();                bitmap.Dispose();                g.Dispose();            }        }        #endregion        #region 4、返回站点路径,如果是虚拟目录,则包含虚拟目录        /// <summary>        /// 返回结果:如果是站点:"/";如果是虚拟目录:"/虚拟目录名/"        /// </summary>        public static string AppName        {            get            {                string appPath = HttpContext.Current.Request.ApplicationPath;                if (appPath.Trim() == "/")                    return "/";                else                    return appPath + "/";            }        }        #endregion        #region 5、返回以字节方式截取字符串        /// <summary>        /// 返回以字节方式载取的字符串        /// </summary>        /// <param name="str"></param>        /// <param name="length"></param>        /// <returns></returns>        public static string GetSubString(string str, int length)        {            string temp = str;            int j = 0;            int k = 0;            for (int i = 0; i < temp.Length; i++)            {                if (Regex.IsMatch(temp.Substring(i, 1), @"[/u4e00-/u9fa5]+"))                    j += 2;                else                    j++;                if (j >= length)                {                    return temp.Substring(0, k - 1);                }                k++;            }            return temp;        }        #endregion        #region 6、简写MD5加密        /// <summary>        /// 返回MD5加密后的密文        /// </summary>        /// <param name="str">原文字符串</param>        /// <param name="code">密文长度:16/32 ,非16则返回32位的密文</param>        /// <returns></returns>        public static string Md5(string str, int code)        {            if (code == 16) //16位MD5加密(取32位加密的9~25字符)             {                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);            }            else//32位加密             {                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();            }        }        #endregion        #region 7、将一个控的内容Render后生成一个字符串        /// <summary>        /// 将一个控的内容Render后生成一个字符串        /// </summary>        /// <param name="ctl"> 用户控件ID</param>        /// <returns></returns>        public static string GetControlRender(System.Web.UI.Control ctl)        {            TextWriter tempWriter = new StringWriter();            ctl.RenderControl(new HtmlTextWriter(tempWriter));            return tempWriter.ToString();        }        #endregion        #region 8、初始化文件夹        /// <summary>        /// 初始化文件夹信息:检查文件夹是否存在,如果文件夹不存在,则建立。         /// </summary>        /// <param name="path">文件夹相对路径</param>        /// <returns>返回文件夹物理路径</returns>        public static string InitFolderPath(string path)        {            //string physicsPath = HttpContext.Current.Server.MapPath(path);            //            string physicsPath = path;            if (!Directory.Exists(physicsPath))            {                Directory.CreateDirectory(physicsPath);            }            return physicsPath;        }        #endregion        #region 9、加密/解密方法:(对称加密:简单方法)        /// <summary>        /// 加密/解密密钥        /// </summary>        public static string Key        {            get            {                return "123456";            }        }        /// <summary>        /// 加密        /// </summary>        /// <param name="Text"></param>        /// <returns></returns>        public static string Encrypt(string Text)        {            return Encrypt(Text, Key);        }        /// <summary>         /// 加密数据         /// </summary>         /// <param name="Text"></param>         /// <param name="sKey">密钥</param>         /// <returns></returns>         public static string Encrypt(string Text, string sKey)        {            DESCryptoServiceProvider des = new DESCryptoServiceProvider();            byte[] inputByteArray;            inputByteArray = Encoding.Default.GetBytes(Text);            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            System.IO.MemoryStream ms = new System.IO.MemoryStream();            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);            cs.Write(inputByteArray, 0, inputByteArray.Length);            cs.FlushFinalBlock();            StringBuilder ret = new StringBuilder();            foreach (byte b in ms.ToArray())            {                ret.AppendFormat("{0:X2}", b);            }            return ret.ToString();        }        /// <summary>        /// 解密        /// </summary>        /// <param name="Text"></param>        /// <returns></returns>        public static string Decrypt(string Text)        {            return Decrypt(Text, Key);        }        /// <summary>         /// 解密数据         /// </summary>         /// <param name="Text"></param>         /// <param name="sKey">密钥</param>         /// <returns></returns>         public static string Decrypt(string Text, string sKey)        {            DESCryptoServiceProvider des = new DESCryptoServiceProvider();            int len;            len = Text.Length / 2;            byte[] inputByteArray = new byte[len];            int x, i;            for (x = 0; x < len; x++)            {                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);                inputByteArray[x] = (byte)i;            }            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));            System.IO.MemoryStream ms = new System.IO.MemoryStream();            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);            cs.Write(inputByteArray, 0, inputByteArray.Length);            cs.FlushFinalBlock();            return Encoding.Default.GetString(ms.ToArray());        }        #endregion        #region 10.生成验证码        /// <summary>        /// 生成验证码        /// </summary>        /// <param name="VNum"></param>        public static void ValidateCode(string VNum)        {            Bitmap Img = null;            Graphics g = null;            MemoryStream ms = null;            int gheight = VNum.Length * 15;            Img = new Bitmap(gheight, 25);            g = Graphics.FromImage(Img);            //背景颜色             g.Clear(Color.White);            //文字字体             Font f = new Font("宋体", 14);            //文字颜色             SolidBrush s = new SolidBrush(Color.Blue);            g.DrawString(VNum, f, s, 3, 3);            ms = new MemoryStream();            Img.Save(ms, ImageFormat.Jpeg);            System.Web.HttpContext.Current.Response.ClearContent();            System.Web.HttpContext.Current.Response.ContentType = "image/Jpeg";            System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());            g.Dispose();            Img.Dispose();            System.Web.HttpContext.Current.Response.End();        }        #endregion    }    #endregion}