取得亂數所產生的英文字母大小寫與數字組合的字串

  • 14875
  • 0
  • C#
  • 2009-09-11

摘要:取得亂數所產生的英文字母大小寫與數字組合的字串

/*
    方法名稱: GetRandomString
    方法說明: 取得亂數所產生的英文字母大小寫與數字組合的字串
    參數說明: length - 要產生的亂數字串長度
    傳回值: string - 亂數字串
    使用範例:
            //code可能為 m0bJ57L7PX08A0ice9sb0Lngu
            string code = Tools.GetRandomString(25);
    */

    public static string GetRandomString(int length)
    {
        Random r = new Random();

        string code = "";

        for (int i = 0; i < length; ++i)
            switch (r.Next(0, 3))
            {
                case 0: code += r.Next(0, 10); break;
                case 1: code += (char)r.Next(65, 91); break;
                case 2: code += (char)r.Next(97, 122); break;
            }


        return code;
    }