Ideas
Use fixedCLientID_(用于分别出这是用户id)
现在的时间
(设备信息+用户名)Md5转换
随机数(确保唯一)
string ++ .
Code
Parameters that need to be entered
length
: How many digits of random numbers are used to generate.
UserName
: The user's username.
public string CreateRandomCode(int length, string UserName) //随机生成客户端ID
{
string LocalTime = DateTime.Now.ToShortTimeString();//获取时间
LocalTime = LocalTime.Replace(":", "");//将符号去掉
string list = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";//list中存放着随机的元素
string UserhostName = Dns.GetHostName() + UserName;//获取主机名和用户名
MD5 mD5 = new MD5CryptoServiceProvider();//创建Md5实例
UserhostName = BitConverter.ToString(mD5.ComputeHash(Encoding.Default.GetBytes(UserhostName)), 4, 4);//生成多长的值,可以自行调参
UserhostName = UserhostName.Replace("-", "");//连接
Random random = new Random();//创建实例
string code = ""; //随机数
for (int i = 0; i < length; i++) //循环得到一个伪随机的数
{
code += list[random.Next(0, list.Length - 1)];
}
string ClientID = "Client_"+ LocalTime + UserhostName + code;//生成客户ID
return ClientID;
}
复制代码
call method
private void button1_Click(object sender, EventArgs e)//C#的Button按钮
{
textBox1.Text= CreateRandomCode(3, textBox2.Text);//最长随机数3位
}
复制代码
achieve effect
expand
Because C# comes with the MD5 class, it is very convenient to use. The following is the usage of the method used this time.
MD5 class method (from official documentation)
ComputeHash(Byte[], Int32, Int32)
Calculates the hash value of the specified range of the specified byte array.
public byte[] ComputeHash (byte[] buffer, int offset, int count);
parameter
- buffer
The input whose hash code is to be calculated.
- offset
The offset in the byte array from which data is used.
- count
The number of bytes used as data in the array.