VB.NET Random String

Generate random strings with the Path.GetRandomFileName Function.
Random String. A random string is sometimes useful. With it, we can store data with a random key. In VB.NET we can generate a random string in many ways. But using Path.GetRandomFileName is one of the simpler ways.Path
Example. Sometimes simpler is better. In the .NET Framework, an included method called Path.GetRandomFileName returns an 8-char file name with a 3-char extension. We can use this method to generate a short, lowercased, random string.

Caution: There are limitations to this approach. Longer strings are not available, and no uppercase letters are included.

And: With the Random class, we could generate letters and numbers and add them to a Char array.

Char Array
VB.NET program that generates random Strings Imports System.IO Module Module1 Public Function GetRandomString() Dim p As String = Path.GetRandomFileName() p = p.Replace(".", "") Return p End Function Sub Main() ' Get two random strings. Dim value As String = GetRandomString() Dim value2 As String = GetRandomString() ' Display the strings. Console.WriteLine(value) Console.WriteLine(value2) End Sub End Module Output qkdqh2lmcev tsx1vo4fdhh
Discussion. Sometimes we need random strings, and the exact characteristics of those strings are not important. For example, I have needed to generate random String keys for a Dictionary. A simple method, like GetRandomString above, suffices.Dictionary
Summary. For serious programs, a custom method that generates a larger range of random characters might be needed. For testing, though, the Path class offers an included random-string generator: GetRandomFileName.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to