Hàm Csharp: Tạo chuỗi ký tự ngẫu nhiên

Có khi bạn cần tạo chuỗi ký tự ngẫu nhiên từ 1 dãy ký tự hoặc tạo lại mật khẩu khi có yêu cầu gửi mật khẩu từ người dùng quên mật khẩu. Hàm sau sẽ thực hiện yêu cầu đó



Hàm này trả về chuỗi ngẫu nhiên với số ký tự cần lầy= SoKyTuMuonLay và lấy từ ChuoiNguon
    public string TaoChuoiNgauNhien(int SoKyTuMuonLay, string ChuoiNguon)
    {
        Random randNum = new Random();
        char[] chars = new char[SoKyTuMuonLay];
        int allowedCharCount = ChuoiNguon.Length;
        for (int i = 0; i < SoKyTuMuonLay; i++)
        {
            chars[i] = ChuoiNguon[(int)((ChuoiNguon.Length) * randNum.NextDouble())];
        }
        return new string(chars);
    }
    
    //Hàm này trả về chuỗi Password ngẫu nhiên [a-z], [0-9] 
    public static string CreateRandomPassword(int PasswordLength)
    {
        string _allowedChars = "abcdefghijkmnopqrstuvwxyz0123456789";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++) { chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())]; } return new string(chars); }
Hàm sau đây sẽ tạo mã ngẫu nhiên chỉ gồm các chữ số
public string MaNgauNhien_So(int codeCount)
{
    string allChar = "0,1,2,3,4,5,6,7,8,9";
    string[] allCharArray = allChar.Split(',');
    string randomCode = "";
    int temp = -1;

    Random rand = new Random();
    for (int i = 0; i < codeCount; i++)
    {
        if (temp != -1)
        {
            rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
        }
        int t = rand.Next(10);
        if (temp != -1 && temp == t)
        {
            return MaNgauNhien_So(codeCount);
        }
        temp = t;
        randomCode += allCharArray[t];
    }
    return randomCode;
}
 Hàm sau đây sẽ tạo chuỗi ngẩu nhiên có cả số và ký tự
public string MaNgauNhien_SoChu(int codeCount)
{
    string allChar = "0,1,2,3,4,5,6,7,8,9
 ,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
    string[] allCharArray = allChar.Split(',');
    string randomCode = "";
    int temp = -1;

    Random rand = new Random();
    for (int i = 0; i < codeCount; i++)
    {
        if (temp != -1)
        {
            rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
        }
        int t = rand.Next(36);
        if (temp != -1 && temp == t)
        {
            return MaNgauNhien_SoChu(codeCount);
        }
        temp = t;
        randomCode += allCharArray[t];
    }
    return randomCode;
}