C# 生成隨機字符串


#region 5.0 生成隨機字符串 + static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
        ///<summary>
        ///生成隨機字符串 
        ///</summary>
        ///<param name="length">目標字符串的長度</param>
        ///<param name="useNum">是否包含數字,1=包含,默認為包含</param>
        ///<param name="useLow">是否包含小寫字母,1=包含,默認為包含</param>
        ///<param name="useUpp">是否包含大寫字母,1=包含,默認為包含</param>
        ///<param name="useSpe">是否包含特殊字符,1=包含,默認為不包含</param>
        ///<param name="custom">要包含的自定義字符,直接輸入要包含的字符列表</param>
        ///<returns>指定長度的隨機字符串</returns>
        public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = null, str = custom;
            if (useNum == true) { str += "0123456789"; }
            if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
            for (int i = 0; i < length; i++)
            {
                s += str.Substring(r.Next(0, str.Length - 1), 1);
            }
            return s;
        } 
        #endregion

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM