How can I generate random alphanumeric strings in C#?
如何在C#中生成随机的8个字符的字母数字字符串?
I heard LINQ is the new black, so here's my attempt using LINQ:
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
(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.)
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
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.)
This implementation (found via google) looks sound to me.
Unlike some of the alternatives presented, this one is cryptographically sound .
using System.Security.Cryptography;
using System.Text;
namespace UniqueKey
{
public class KeyGenerator
{
public static string GetUniqueKey(int maxSize)
{
char[] chars = new char[62];
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
byte[] data = new byte[1];
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
crypto.GetNonZeroBytes(data);
data = new byte[maxSize];
crypto.GetNonZeroBytes(data);
}
StringBuilder result = new StringBuilder(maxSize);
foreach (byte b in data)
{
result.Append(chars[b % (chars.Length)]);
}
return result.ToString();
}
}
}
Picked that one from a discussion of alternatives here
链接地址: http://www.djcxy.com/p/17718.html上一篇: 在特定范围内使用JavaScript生成随机整数?
下一篇: 我如何在C#中生成随机字母数字字符串?