Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Anyone can explain to me the following, what does the do and mean?


C#
private string RandomString(int StrLength)
    {
        string CharsList = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*";
        char[] chars = CharsList.ToCharArray();

        RNGCryptoServiceProvider cryptoGen = new RNGCryptoServiceProvider();
        byte[] ByteData = new byte[StrLength];
        cryptoGen.GetBytes(ByteData);

        StringBuilder ResultStr = new StringBuilder();
        foreach (byte byt in ByteData)
        {
            ResultStr.Append(chars[byt % chars.Length]);
        }
        return ResultStr.ToString();

    }
Posted
Updated 11-Feb-12 22:54pm
v2

Hello,

C#
private string RandomString(int StrLength) //A method to generate a random string which its lenght is StrLength.

{
        string CharsList = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*"; //Clear
        char[] chars = CharsList.ToCharArray(); //Converts CharsList to a Char array. for example: char[0]='a', char[1] = 'b', char[25]= 'z' and ....
 
        RNGCryptoServiceProvider cryptoGen = new RNGCryptoServiceProvider(); //Creates a new instance of the RNGCryptoServiceProvider. It's a Random Number Generator.
 
        byte[] ByteData = new byte[StrLength]; //Creates an byte array to hold the random value. Its lenght is equal to CharsList.Lenght

        cryptoGen.GetBytes(ByteData); // Fills the array (ByteData) with a random value.

 
        StringBuilder ResultStr = new StringBuilder(); //Creates an instance of StringBuilder to create dynamic strings and avoid unnecessary garbage collection. 
//It's better than: 
// string ResultStr = string.Empty;
//foreach (byte byt in ByteData)
//{
//            ResultStr += chars[byt % chars.Length];
//}

        foreach (byte byt in ByteData)//Measuring Generated array (ByteData) 
        {
            ResultStr.Append(chars[byt % chars.Length]);//Packing generated chars as a string.
// [byt % chars.Length] for creating a number >= 0 and < StrLenght
        }
        return ResultStr.ToString(); //It's crystal clear !
 
}
 
Share this answer
 
v2
All it does is generate a random string of bytes, made up of the upper and lower case letters, plus a few special characters.
It probably isn't much use - it starts well by using a strong random sequence generator, then throws away much of that data to generate it's string.

You could have got this pretty easily from MSDN: RNGCryptoServiceProvider.GetBytes Method[^] - so why are you asking? What part of it confuses you?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900