• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
遥远的梦
--心有多大, 世界就有多大
博客园    首页    新随笔    联系   管理    订阅  订阅
验证码制作之四: 位数可改变内容可扩展的验证码产生方法
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public string RandomNum(int Len)
    {
        string str = "0,1,2,3,4,5,6,7,8,9,";
        str += "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,";
        str += "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[] s = str.Split(new char[] { ','});//将字符串拆分成字符串数组
        string strNum = "";
        int tag = -1;//用于记录上一个随机数的值,避免产生两个重复值
        Random rnd = new Random();
        //产生一个长度为Len的随机字符串
        for (int i = 1; i <= Len; i++)
        {
            if (tag == -1)
            {
                rnd = new Random(i*tag*unchecked((int)DateTime.Now.Ticks));//初始化一个Random实例
            }
            int rndNum = rnd.Next(61);//返回小于61的非负随机数
            //如果产生与前一个随机数相同的数,则重新生成一个新随机数
            if (tag != -1 && tag == rndNum)
            {
                return RandomNum(1);
            }
            tag = rndNum;
            strNum += s[rndNum];
        }
        return strNum;
    }
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (this.txtLen.Text != "")
        {
            int l = Convert.ToInt32(this.txtLen.Text.Trim());
            this.labNum.Text = RandomNum(l);
        }
    }
}

posted on 2008-09-04 11:36  子逸  阅读(547)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3