PureSc0pe Posted July 24, 2004 Posted July 24, 2004 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? Quote It's not impossible, it's Inevitable.
keitsi Posted July 24, 2004 Posted July 24, 2004 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; } Quote BS - Beer Specialist
PureSc0pe Posted July 24, 2004 Author Posted July 24, 2004 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?Line Generator.zip Quote It's not impossible, it's Inevitable.
keitsi Posted July 24, 2004 Posted July 24, 2004 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. Quote BS - Beer Specialist
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.