protected void Page_Load(object sender, EventArgs e)
    {
        string[] password = new string[3];
        //Label1.Text = Createpassword();
        for (int i = 0; i < 3; i++)
        {
            password[i] = Createpassword();
        }
        Label1.Text = password[0];
        Label2.Text = password[1];
        Label3.Text = password[2];
    }
    public static string Createpassword()
    {
        string a = "";
        string validator = "abcdefghijklmnopqrstuvwxyz0123456789";
        string[] b = new string[3];
        Random rnd = new Random();
        for (int i=1;i < 5;i++)
        {
            a += validator[rnd.Next(validator.Length)];
          
        }
        return a;
    }我想一次生成多个随机密码,为什么这样写产生的全都一样呢,该如何该?

解决方案 »

  1.   

    月经问题...for执行太快了,Windows时钟精度大约15毫秒,也就是说15毫秒内产生的伪随机数种子不变...去搜索一下旧帖子...
      

  2.   

    你可以用Guid的HashCode做种子。不过重复的概率小一些罢了。
      

  3.   

    你应该把初始化Random放到最上层循环之外...或者换一个更高精度的种子发生器...
      

  4.   

    Math.Random不太随机,用System.Security.Cryptography.RandomNumberGenerator效果很好!
            public static string Createpassword()
            {
                string a = "";
                string validator = "abcdefghijklmnopqrstuvwxyz0123456789";
                System.Security.Cryptography.RandomNumberGenerator rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();
                byte[] buffer = new byte[4];
                rnd.GetBytes(buffer);
                for (int i = 0; i < buffer.Length; i++)
                {
                    int idx = buffer[i] % validator.Length;
                    a += validator[idx];
                }
                return a;
            }