Click to See Complete Forum and Search --> : [RESOLVED] Random string


Marraco
June 4th, 2008, 10:33 AM
¿there are already some function in .NET which returns a random string?

(Is better if it contains chars which humans do not use frequently, like ╚)

maybe there are some to generate random keys.

this generate random paths:

System.IO.Path.GetRandomFileName() As String
for example, it returns:"gdhxyjvj.fnf"

Is the best I have, but I would like less usual chars, and I are being lazy to write a random routine.

An obscure class is System.Security.Cryptography. Looks promising, but I can't locate a random string function.
_

HairyMonkeyMan
June 4th, 2008, 11:57 AM
Private Function GenerateKey(ByVal KeyLength As Integer) As String
Dim RandomClass As New Random
Dim Key As String = ""

For i As Integer = 1 To KeyLength
Dim iNextRnd As Integer = RandomClass.Next(0, 255)
Key &= Chr(iNextRnd).ToString
Next
Return Key
End Function

Marraco
June 4th, 2008, 12:51 PM
Private Function GenerateKey(ByVal KeyLength As Integer) As String
Dim RandomClass As New Random
Dim Key As String = ""

For i As Integer = 1 To KeyLength
Dim iNextRnd As Integer = RandomClass.Next(0, 255)
Key &= Chr(iNextRnd).ToString
Next
Return Key
End FunctionI eventually made:
Public Function RandomString(ByVal Lenght As Integer) As String
Dim Answer As New System.Text.StringBuilder()
For i As Integer = 1 To Lenght ' for character 1 to Lenght
Randomize()
Answer.Append(Chr(256 * Rnd()))
Next i
Return Answer.ToString
End FunctionAnd your code made me do:
Public Function RandomString(ByVal Lenght As Integer) As String
Dim RandomClass As New Random
Dim Answer As New System.Text.StringBuilder()

For i As Integer = 1 To Lenght ' for character 1 to Lenght
Answer.Append(Chr(RandomClass.Next(0, 255)))
Next i
Return Answer.ToString
End FunctionWhich I think is better.
Thanks you.
_

Shuja Ali
June 4th, 2008, 12:59 PM
What exactly is the requirement?

Do you just want a random string or are you looking for encryption?

Marraco
June 4th, 2008, 01:39 PM
What exactly is the requirement?

Do you just want a random string or are you looking for encryption?Just random string. I need it to have a low probability to be created/utilised/needed by the User.

Is only needed to this thread: Smallest and Longest String (http://www.codeguru.com/forum/showthread.php?t=454332)


I hate writing long lines of code, when performance is not a concern, and was also looking for learn new .NET resources.
_

HairyMonkeyMan
June 5th, 2008, 02:51 AM
just a side note:

you should store the RandomClass reference as a module-wide variable.. each time it is instantiated, it reverts back to the first character and outputs the same sequence. If it is module wide, you only need to instantiate it once.

Regards