How can I generate random 8 character alphanumeric strings in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
This implementation (found via google) looks sound to me.
Unlike some of the alternatives presented, this one is cryptographically sound.
Picked that one from a discussion of alternatives here
Not as elegant as the Linq solution. (-:
(Note: The use of the Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)
Here is a variant of Eric J's solution, i.e. cryptographically sound, for WinRT (Windows Store App):
If performance matters (especially when length is high):
Question: Why should I waste my time using
Enumerable.Range
instead of typing in"ABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
?Answer: Magic strings are BAD. Did ANYONE notice there was no "
I
" in my string at the top? My mother taught me not to use magic strings for this very reason...n.b. 1: As many others like @dtb said, don't use
System.Random
if you need cryptographic security...n.b. 2: This answer isn't the most efficient or shortest, but I wanted the space to separate the answer from the question. The purpose of my answer is more to warn against magic strings than to provide a fancy innovative answer.
I was looking for a more specific answer, where I want to control the format of the random string and came across this post. For example: license plates (of cars) have a specific format (per country) and I wanted to created random license plates.
I decided to write my own extension method of Random for this. (this is in order to reuse the same Random object, as you could have doubles in multi-threading scenarios). I created a gist (https://gist.github.com/SamVanhoutte/808845ca78b9c041e928), but will also copy the extension class here:
Just some performance comparisons of the various answers in this thread:
Methods & Setup
Results
Tested in LinqPad. For string size of 10, generates:
And the performance numbers tend to vary slightly, very occasionally
NonOptimized
is actually faster, and sometimesForLoop
andGenerateRandomString
switch who's in the lead.