Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I'm trying to make a very small application that only has a button and a listbox. I need it create a random string of 16 letters, numbers, and symbols mixed together...

 

example... I press the button, the listbox then reads:

 

hN8^7#mL15Lk%7H@

 

have it mix in numbers, letters, and symbols...string of 16 each time button is pressed...

 

How would I go about doing this?

It's not impossible, it's Inevitable.
Posted

Here is my implementation. I didn't use Const for those few variables for mono compability (because of this bug).

 

	/// <summary>
	/// Generates given count of random lowercase letters
	/// </summary>
	/// <param name="count">How many letters to generate</param>
	/// <returns>String of generated letters</returns>
	public static string RandomLetters(int count)
	{

		byte[] bytes;
		bytes = new byte[count];
		System.Security.Cryptography.RandomNumberGenerator rnd = System.Security.Cryptography.RandomNumberGenerator.Create();
		rnd.GetBytes(bytes);
		
		byte min=97; // ascii range: 97 (a) - 122 (z)
		byte max=122;
		int range = max - min + 1;
		float rangefactor = ((float) range) / 255; // letter ascii code range (~28) against 0 - 255 -> 0,something

		byte[] newbytes = new byte[count];

		for (byte k=0;k<bytes.Length;k++)
		{
			newbytes[k] = System.Convert.ToByte(((((float) bytes[k]) * rangefactor) + (float) min));
		}
		string str = System.Text.ASCIIEncoding.ASCII.GetString(newbytes,0,newbytes.Length);
		Debug.WriteLine("RandomLetters() returning '" + str + "'");
		return str;
}

BS - Beer Specialist
Posted
Parts of that didn't make sense while I was implementing it...Can you d/l the enclosed zip file and put your code where it needs to be and then upload it?

Just add the method to a class - then call it using

MessageBox.Show(ClassNameWhereTheMethodIsIn.RandomLetters(10));

for example. The method is static and must be used without class initialization (straight from class, not object).

 

There's not much to implement, just use the function ;)

 

Oh and this can only generate lowercase letters. You'll have to modify it to suite your needs. Also, the ASCII range might be wrong for 1 or two bytes, I haven't tested this function enough.

BS - Beer Specialist

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...