Thứ Hai

Hàm tạo mã ngẫu nhiên

Hàm tạo mã ngẫu nhiên chỉ gồm chữ số, cả số cả ký tự ...
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;
}
hmweb

0 nhận xét:

Đăng nhận xét

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Blogger Templates