Membership Generate Password alphanumeric only password?

前端 未结 7 2137
独厮守ぢ
独厮守ぢ 2020-12-28 13:11

How can I use Membership.GeneratePassword to return a password that ONLY contains alpha or numeric characters? The default method will only guarantee a minimum and not a max

7条回答
  •  情歌与酒
    2020-12-28 13:32

    Going from @SollyM's answer, putting a while loop around it, to prevent the very unlikely event of all characters, or too many characters being special characters, and then substring throwing an exception.

    private string GetAlphaNumericRandomString(int length)
    {
        string randomString = "";
        while (randomString.Length < length)
        {
          //generates a random string, of twice the length specified, to counter the 
          //probability of the while loop having to run a second time
          randomString += Membership.GeneratePassword(length * 2, 0);
    
          //replace non alphanumeric characters
          randomString = Regex.Replace(randomString, @"[^a-zA-Z0-9]", m => "");
        }
        return randomString.Substring(0, length);
    }
    

提交回复
热议问题