public partial class Verify : System.Web.UI.Page
{
    //页面加载时运行此程序
    protected void Page_Load(object sender, EventArgs e)
    {    //生成4位的验证码
        string tmp = RndNum(4); //取随机码
        this.Session["verify"] = tmp.ToLower();//将获取的随机码放入Session,以便以后比较
        this.ValidateCode(tmp); // 输出图片
    }
    //生成验证码图片
    private void ValidateCode(string VNum)
    {
        int gheight = VNum.Length * 12;//设置图片的长度
        //开始绘制,绘制后释放资源
        using (System.Drawing.Bitmap Img = new System.Drawing.Bitmap(gheight, 25))
        {
            //开始画图,画完了释放资源
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(Img))
            {
                g.Clear(Color.White); //背景颜色
                Font f = new Font("Arial Black", 10); //文字字体
                SolidBrush s = new SolidBrush(Color.Black); //文字颜色
                g.DrawString(VNum, f, s, 3, 3);//画图
                MemoryStream ms = new MemoryStream();//内存流
                Img.Save(ms, ImageFormat.Jpeg);//生成jpg图片
                Response.ClearContent();//先清除未输出内容
                Response.ContentType = "image/Jpeg";//输出类型
                Response.BinaryWrite(ms.ToArray());//将内存流输出
            }
        }
        Response.End();//输出完毕
    }
    //根据传入的数字,生成随机数个数
    private string RndNum(int VcodeNum)
    {
        string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";//随机数范围
        string[] VcArray = Vchar.Split(new Char[] { ',' });//随机数数组范围
        string VNum = "";
        int temp = -1;
        Random rand = new Random();//随机变量
        //循环生成要求的随机数
        for (int i = 1; i < VcodeNum + 1; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化
            }
            int t = rand.Next(35);//生成随机数
            if (temp != -1 && temp == t)
            {
                //递归调用
                return RndNum(VcodeNum);
            }
            temp = t;
            VNum += VcArray[t];//在随机数数组范围中获取字母或者数字
        }
        return VNum;//得到随机的字符串   
}

}