怎样才能在C#中的随机字母数字串? [英] How can I generate random alphanumeric strings in C#?

查看:349
本文介绍了怎样才能在C#中的随机字母数字串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

怎样才能在C#中随机8个字符的字母数字串?

How can I generate random 8 character alphanumeric strings in C#?

推荐答案

我听说LINQ是新的黑色,所以这里的使用LINQ我尝试:

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());
}

注:的使用Random类的使这个不适合任何与安全有关的,如创建密码或令牌结果
           使用RNGCryptoServiceProvider类,如果你需要一个强大的随机数生成器)

(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.)

这篇关于怎样才能在C#中的随机字母数字串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆