[VB.NET] 產生英數混合隨機字串

  • 620
  • 0
  • 2022-02-14

  產生由英文大小寫、數字混合的隨機字串。

 

Public Function str_CreateRandomString(ByVal int_StrLength As Integer) As String

    Dim strlst_AlphabetAndNumber As New List(Of String)
    Dim cls_RamdomNumber As Random
    Dim int_RandomSeed As Integer
    Dim str_RandomString As String

    str_RandomString = String.Empty

    ' 將大寫字母A到Z加入List
    For int_ASCII As Integer = AscW("A") To AscW("Z")
    strlst_AlphabetAndNumber.Add(ChrW(int_StartASCII))
    Next

    ' 將小寫字母a到z加入List
    For int_ASCII As Integer = AscW("a") To AscW("z")
    strlst_AlphabetAndNumber.Add(ChrW(int_StartASCII))
    Next

    ' 將數字0到9加入List
    For int_ASCII As Integer = AscW("0") To AscW("9")
    strlst_AlphabetAndNumber.Add(ChrW(int_StartASCII))
    Next

    ' 以當前時間為種子產生亂數
    int_RandomSeed = CInt(DateTime.Now.ToString("ddHHmmss"))
    cls_RamdomNumber = New Random(int_RandomSeed)

    ' 每產生一個亂數,就取一次List長度的餘數,再從List中取出對應的字母或數字
    For int_ArrIdx As Integer = 0 To int_StrLength - 1
    str_RandomString += strlst_AlphabetAndNumber(cls_RamdomNumber.Next Mod 62)
    Next int_ArrIdx

    Return str_RandomString

End Function