12/9/11

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;
}
Bookmark and Share

0 comments:

Post a Comment

Next previous home

Cộng đồng yêu thiết kế Việt Nam Thiet ke website, danang