Adsence750x90

Friday, November 14, 2008

How to create Random string with numbers using C#

am providing a function to get random numbers. this function returning RandomKey. programmers can use this key fro captcha creation.

public string RandomStringKeys()
{
string returnString = string.Empty;
string Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string numbers = "0123456789";
char[] letterArray = Letters.ToCharArray();
char[] numberArray = numbers.ToCharArray();
Random objrandomNumber = new Random();
byte[] selection = Encoding.ASCII.GetBytes(objrandomNumber.Next(111111, 999999).ToString());
BitArray bArray = new BitArray(selection);

string binaryString = string.Empty;
int t = 0;
int f = 0;

for (int i = 0; i < bArray.Length; i++)
{
if (bArray[i])
{
binaryString += 1;
t++;
}
else
{
binaryString += 0;
f++;
}
}

char[] enCodeString = binaryString.Substring(objrandomNumber.Next(1, 8), objrandomNumber.Next(4, 8)).ToCharArray();
for (int i = 0; i < enCodeString.Length; i++)
{
if (enCodeString[i] == '1')
{
returnString += letterArray[objrandomNumber.Next(0, 51)];
}
else
{
returnString += numberArray[objrandomNumber.Next(0, 9)];
}

}
return returnString;

}

No comments: