获取随机字符

private static Random rd = new Random();
        
        /// <summary>
        /// 获取指定长度的随机数
        /// </summary>
        /// <param name="pwdLength"></param>
        /// <returns></returns>
        public static string GetNewCode(int pwdLength)
        {

            byte[] pwd = new byte[pwdLength];

            int i;
            for (i = 0; i < pwdLength; i++)
            {

                int a = 0;
                //while 后的条件用来限定密码的字符集
                while ((!((a >= 48 && a <= 57))) || (a == 48 && i == 0))    //| (a>=65 && a<=90) || (a>=97 && a<=122)) )
                {
                    a = rd.Next(48, 60);
                }
                pwd[i] = (byte)a;
            }

            return new string(UnicodeEncoding.ASCII.GetChars(pwd)).ToLower();
        }

        /// <summary>
        /// 获取指定长度的随机字母(小写)
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetNewLetter(int length)
        {

            byte[] bytes = new byte[length];
            int temp = 0;
            for (int i = 0; i < length; i++)
            {
                //while 后的条件用来限定密码的字符集
                while (!(temp >= 97 && temp <= 122))    //随机小写字母
                {
                    temp = rd.Next(97, 122);
                }
                bytes[i] = (byte)temp;
                temp = 0;
            }

            return new string(UnicodeEncoding.ASCII.GetChars(bytes)).ToLower();
        }
原文地址:https://www.cnblogs.com/mengxingxinqing/p/3164939.html