I'd like to generate random unique strings like the ones being generated by MSDN library:
http://msdn.microsoft.com/en-us/library/t9zk6eay.aspx, for example. A string like 't9zk6eay' should be generated.
I'd like to generate random unique strings like the ones being generated by MSDN library:
http://msdn.microsoft.com/en-us/library/t9zk6eay.aspx, for example. A string like 't9zk6eay' should be generated.
This has been asked for various languages. Here's one question about passwords which should be applicable here as well.
If you want to use the strings for URL shortening, you'll also need a Dictionary<> or database check to see whether a generated ID has already been used.
This works perfect for me
Try combination between Guid and Time.Ticks
If you want an alphanumeric strings with lowercase and uppercase characters ([a-zA-Z0-9]), you can use Convert.ToBase64String() for a fast and simple solution.
As for uniqueness, check out the birthday problem to calculate how likely a collission is given (A) the length of the strings generated and (B) the number of strings generated.
Using Guid would be a pretty good way, but to get something looking like your example, you probably want to convert it to a Base64 string:
I get rid of "=" and "+" to get a little closer to your example, otherwise you get "==" at the end of your string and a "+" in the middle. Here's an example output string:
"OZVV5TpP4U6wJthaCORZEQ"
Update 2016/1/23
If you find this answer useful, you may be interested in a simple (~500 SLOC) password generation library I published:
Then you can generate random strings just like in the answer below:
One advantage of the library is that the code is better factored out so you can use secure randomness for more than generating strings. Check out the project site for more details.
Original Answer
Since no one has provided secure code yet, I post the following in case anyone finds it useful.
Thanks to Ahmad for pointing out how to get the code working on .NET Core.