c#产生随机字符串的两种方法

// c#产生随机字符串的两种方法
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace 随机产生字符串
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Random random = new Random();
        private string chars = "ABCDEFGHIJKLMNOPQRSTUWVXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        private void button1_Click(object sender, EventArgs e)
        { 
            this.textBox1.Clear();
            this.textBox1.AppendText(radomstrs(chars, 8));
        }

        /// 
        /// 随机字符方法一 遍历返回
        /// 
        /// 随机字符串源
        /// 返回随机的字符串个数
        /// 
        private string radomstrs(string chars ,int length)
        {
            string strs = string.Empty;
            for (int i = 0; i < length; i++)
            {
                strs += chars[random.Next(chars.Length)];
            }
            return strs;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.textBox1.Clear();
            this.textBox1.AppendText(radomstrsbyling(chars, 8));
            
        }

        /// 
        ///  随机字符方法二 System.Linq.Enumerable;
        /// 
        /// 随机字符串源
        /// 返回随机的字符串个数
        /// 
        private string radomstrsbyling(string chars, int length)
        {
            return new string( Enumerable.Repeat(chars, length).Select(s => s[random.Next(chars.Length)]).ToArray()); 
        }
    }
}
Random random = new Random();
			byte[] bytes = new byte[random.Next(0, 10000)];
			System.Security.Cryptography.RNGCryptoServiceProvider rNGCryptoServiceProvider = new System.Security.Cryptography.RNGCryptoServiceProvider();
			rNGCryptoServiceProvider.GetBytes(bytes);
			int num = BitConverter.ToInt32(bytes, 0);

你可能感兴趣的:(C#,随机字符串)