Is there any class in .Net 4.0 that be able to create random string?
I want to create a random string (about 20 characters length). Is there any built-in class in .net that able to create random stri开发者_StackOverflowng?
You could create a Guid then convert it to a string.
Guid.NewGuid().ToString()
This will give you a random string with the length 36, but you could then just trim this down to 20.
Path.GetRandomFileName Method
The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name. Unlike GetTempFileName, GetRandomFileName does not create a file. When the security of your file system is paramount, this method should be used instead of GetTempFileName.
Use Guid.NewGuid().ToString().Replace('-', default(Char)).Substring(0, 20)
How about:
string myString = Guid.NewGuid().ToString().Substring(0, 20);
You should try TestApi, more specifically the Text String Generation API.
Path.GetRandomFileName() will create you a random file name - think it's only 11 chars long though.
Generating Random Strings in .NET
http://www.keyvan.ms/generating-random-strings-in-net
Article covers GUID, Random Numbers and RNGCryptoServiceProvider methods to generate random string
Here is a function I wrote that uses GetRandomFileName() to get a random string of any length.
''' <summary>
''' Obtain a random string of any length.
''' </summary>
''' <param name="length">Desired length of string.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetRandomString(ByVal length As Integer) As String
Dim sb As New StringBuilder(length)
While (sb.Length < length)
' GetRandomFileName returns a "cryptographically strong" random filename ex: "bfdbn2af.sxq"
sb.Append(IO.Path.GetRandomFileName().Replace(".", ""))
End While
' strip the excess characters
sb.Remove(length - 1, sb.Length - length)
Return sb.ToString()
End Function
精彩评论