Home
Search
VB.NET Random StringGenerate 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.
Random
A simple approach. Using Path.GetRandomFileName is one of the simpler ways to generate a random string. This can be sufficient for many purposes.
Path
Example. In .NET, an included method called Path.GetRandomFileName returns an 8-char file name with a 3-char extension. This will generate a short, lowercased, random string.
Warning There are limitations to this approach. Longer strings are not available, and no uppercase letters are included.
Replace We use the string Replace function to eliminate the period from the random string.
Replace
Info With the Random class, we could generate letters and numbers and add them to a Char array.
Char Array
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
qkdqh2lmcev tsx1vo4fdhh
A discussion. Sometimes we need random strings, and the exact characteristics of those strings are not important. A simple method, like GetRandomString, suffices.
Info For example, I have needed to generate random String keys for a Dictionary for testing performance.
Dictionary
A summary. For serious programs, a custom method might be needed. For testing, though, the Path class offers an included random-string generator: GetRandomFileName.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on 9/7/2022 (rewrite).
Home
© 2007-2022 sam allen.
see site info on the changelog.