1

I want to make a random character generator with numbers in vb.net, I know how to make a random number generator but not numbers mixed with letters. I want it to be around 15-20 characters. Something like this: F53Gsfdsj637jfsj5kd8

Thanks ahead!

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
koolboy5783
  • 309
  • 2
  • 5
  • 8
  • possible duplicate of [How can I generate random 8 character, alphanumeric strings in C#?](http://stackoverflow.com/questions/1344221/how-can-i-generate-random-8-character-alphanumeric-strings-in-c) – IAbstract Mar 31 '13 at 03:17
  • although the referenced question is C#, a little research on MSDN will show you the same commands in VB.Net. – IAbstract Mar 31 '13 at 03:20

1 Answers1

7

You're mostly there once you have a random number generator. From there, just pick a random character within a collection of valid characters. The simplest way would be something like:

dim validchars as string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

dim sb as new StringBuilder()
dim rand as new Random()
for i as Integer = 1 to 10
    dim idx as Integer = rand.Next(0, validchars.Length)
    dim randomChar as char = validchars(idx)
    sb.Append(randomChar)
next i

dim randomString = sb.ToString()

Of course, clean up the syntax a bit, and maybe use a constant value for the chars and length, a variable value for the number of digits, etc.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • Not sure where the downvote came from, but if it's because I spelled out the valid characters instead of using the technique Dan used in the other answer, there is merit in doing it this way. If this is to be used in human-readable codes, you'll likely want to exclude potentially confusing characters like `Il10O`, which is easy to do here. Also you can add characters to the valid list easily, in case you want a couple special characters in there. Also, there's less confusion in the code - `rand.next(48, 122)` will never give you `'z'` because the second number (122) is exclusive in the method. – Joe Enos Mar 31 '13 at 06:00