c#生成无重复的验证码

来源:互联网 发布:excel怎么编程 编辑:程序博客网 时间:2024/05/20 01:44

最近公司项目做了代金卷的业余,需要生成随机的8位数字,字母组合的条码。现贴出2种程序源码供大家学习和参考。

方法1.

       private static char[] constant = { '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', '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' };
        public string pxkt_GetCharFont(int strLength)
        {
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
            Random rd = new Random(Guid.NewGuid().GetHashCode());//保证生成的随机字符永远不重复 

         // Random rd= new Random(); //不能写成这样,数目小的60条左右没问题,多了就会有很多重复
            for (int i = 0; i < strLength; i++)
            {
                newRandom.Append(constant[rd.Next(62)]);
            }
            return newRandom.ToString();
        }

方法2

public string RandomNum(int n) //
    {
        //定义一个包括数字、大写英文字母和小写英文字母的字符串
        string strchar = "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,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";
        //将strchar字符串转化为数组
        //String.Split 方法返回包含此实例中的子字符串(由指定Char数组的元素分隔)的 String 数组。
        string[] VcArray = strchar.Split(',');
        string VNum = "";
        //记录上次随机数值,尽量避免产生几个一样的随机数          
        int temp = -1;
        //采用一个简单的算法以保证生成随机数的不同
          Random rd = new Random(Guid.NewGuid().GetHashCode());//保证生成的随机字符永远不重复 

         // Random rd= new Random(); //不能写成这样,数目小的60条左右没问题,多了就会有很多重复

        for (int i = 1; i < n + 1; i++)
        {
            if (temp != -1)
            {
                //unchecked 关键字用于取消整型算术运算和转换的溢出检查。
                //DateTime.Ticks 属性获取表示此实例的日期和时间的刻度数。
                rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
            }
            //Random.Next 方法返回一个小于所指定最大值的非负随机数。
            int t = rand.Next(61);
            if (temp != -1 && temp == t)
            {
                return RandomNum(n);
            }
            temp = t;
            VNum += VcArray[t];
        }
        return VNum;//返回生成的随机数
    }
 

}

 

原创粉丝点击