c# 产生随机字符串,包括大小写字母和数字

 #region MyRegion
        //產生密碼
        protected static string GetPwd()
        {
           return CreateRandomNum123(2) + CreateRandomNumABC(3) + CreateRandomNumabc(3); 
        }
        protected static string CreateRandomNum123(int NumCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9"; // 
            string[] allCharArray = allChar.Split(',');//拆分成数组
            string randomNum = "";
            int temp = -1;//记录上次随机数的数值,尽量避免产生几个相同的随机数

            Random rand = new Random();
            for (int i = 0; i < NumCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(10);
                if (temp == t)
                {
                    return CreateRandomNum123(NumCount);
                }
                temp = t;
                randomNum += allCharArray[t];
            }
            return randomNum;
        }
        protected static string CreateRandomNumABC(int NumCount)
        {
            string allChar = "A,B,D,E,F,G,H,I,J,K,L,M,N,Q,R,T,W,Y"; // 
            string[] allCharArray = allChar.Split(',');//拆分成数组
            string randomNum = "";
            int temp = -1;//记录上次随机数的数值,尽量避免产生几个相同的随机数

            Random rand = new Random();
            for (int i = 0; i < NumCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(18);
                if (temp == t)
                {
                    return CreateRandomNumABC(NumCount);
                }
                temp = t;
                randomNum += allCharArray[t];
            }
            return randomNum;
        }
        protected static string CreateRandomNumabc(int NumCount)
        {
            string allChar = "a,b,d,e,f,g,h,i,j,k,l,m,n,q,r,t,w,y"; // 
            string[] allCharArray = allChar.Split(',');//拆分成数组
            string randomNum = "";
            int temp = -1;//记录上次随机数的数值,尽量避免产生几个相同的随机数

            Random rand = new Random();
            for (int i = 0; i < NumCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(18);
                if (temp == t)
                {
                    return CreateRandomNumabc(NumCount);
                }
                temp = t;
                randomNum += allCharArray[t];
            }
            return randomNum;
        }
        #endregion

 

posted @ 2014-01-15 14:22  sirili  阅读(1432)  评论(1编辑  收藏  举报