Mic*_*paz 6 c# random encoding ascii numericupdown
这是代码:(passwordLengthBox是NumericUpDown Box,r和k是随机数)
private void generateButton_Click(object sender, EventArgs e)
{
int r, k;
int passwordLength = (Int32)passwordLengthBox.Value;
string password = "";
char[] upperCase = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
char[] lowerCase = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
int[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
Random rRandom = new Random();
for (int i = 0; i < passwordLength; i++)
{
r = rRandom.Next(3);
if (r == 0)
{
k = rRandom.Next(0, 25);
password += upperCase[k];
}
else if (r == 1)
{
k = rRandom.Next(0, 25);
password += lowerCase[k];
}
else if (r == 2)
{
k = rRandom.Next(0, 9);
password += numbers[k];
}
}
textBox.Text = password;
}
Run Code Online (Sandbox Code Playgroud)
这个程序的作用是创建一个随机密码,包括字母(大写和小写)和我选择的长度的数字.问题是,该程序并没有使密码长度为我选择.
例如:如果我在NumericUpDown Box(passwordLengthBox)中键入5,设置密码长度,有时它会给我5个字符长的密码,有时6/7/8个字符长密码.
我的错是什么?
Mar*_*zek 14
问题在这里:
int[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
Run Code Online (Sandbox Code Playgroud)
每次附加一个数字时,使用该声明password
将被视为ASCII编号,而不是实际值.所以你要添加48到57之间的整数,结果字符串会比预期更长.
例如,当6
生成为随机数时,您将类似于:添加((int)'6').ToString()
到您的password
变量中,实际添加的内容54
而不是6
.
声明该数组char[]
,它将正常工作.
你可以试试这个小方法.
public static string Random(int length)
{
try
{
byte[] result = new byte[length];
for (int index = 0; index < length; index++)
{
result[index] = (byte)new Random().Next(33, 126);
}
return System.Text.Encoding.ASCII.GetString(result);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
Run Code Online (Sandbox Code Playgroud)
与此唯一的区别是它也会使用字母数字字符,例如它可能会生成字符串 f6Dx3$5d£4hG7
看看www.asciitable.com并找出你想要使用的角色范围.
对于内森来说,如果你确切地知道你想要哪些角色,这是你可以做到的另一种方式......
public static string Random(int length)
{
string allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
return new string(allowed
.OrderBy(o => Guid.NewGuid())
.Take(length)
.ToArray());
}
Run Code Online (Sandbox Code Playgroud)