我试着做一个 while 循环,我知道问题所在,我只是不知道如何解决它。我使用的 int 永远不会更新,使代码无用......我使用 Visual Studio,windows fom 应用程序,如果它改变了什么......对不起,长度,但我不知道问题出在哪里。 (输入 1 和 2 是文本框...)我使用的文本文件如下所示: 用户名:换行 (costum text) 换行 密码:换行 (costum text) 换行 用户名:换行 ...
代码如下:
public partial class Form1 : Form
{
//This is part of the problem
int search = 0;
//This is part of the problem (end)
public void OK_Click(object sender, EventArgs e)
{
string path = @"filePath.txt";
var count = File.ReadLines(path).Count();
string user = File.ReadLines(path).Skip(search + 1).Take(1).First();
string pass = File.ReadLines(path).Skip(search + 3).Take(1).First();
//Main problem
if (Input1.Text != "" && Input2.Text != "")
{
while (Input1.Text == user && Input2.Text == pass)
{
if (search < count)
{
search = search + 4;
}
}
if (search < count)
{
MessageBox.Show("worked");
search = 0;
}
}
//Main problem (end)
}
}
答案 0 :(得分:0)
这可以大大简化。用户名和密码在交替行上,因此需要在循环内声明它们。您还可以使用 for 循环来控制在循环的每次迭代结束时跳到下一个用户名/密码组合。而且您不需要多次执行 File.ReadLines,这会导致它多次访问磁盘以获取您可以在内存中保存一次的内容。
您还应该重命名文本框,以使用代表它们应包含的数据的名称。例如 UsernameTextbox 而不是 Input1。
public void OK_Click(object sender, EventArgs e)
{
string path = @"filePath.txt";
var fileLines = File.ReadLines(path);
var authenticatedSuccessfully = false;
for (int line = 0; line < fileLines.Length - 1; line += 2)
{
var user = fileLines[line];
var password = fileLines[line + 1];
if (UsernameTextbox.Text == user && PasswordTextBox.Text == pass)
{
authenticatedSuccessfully = true;
break;
}
}
if (authenticatedSuccessfully)
{
MessageBox.Show("You are logged in!");
}
else
{
MessageBox.Show("Incorrect username or password!");
}
}
当然……您应该记住,这根本不安全。在现实世界中,密码应该是一种散列和加盐的方式。然后,当用户想要验证时,您再次散列密码并将其与存储的值进行比较。如果匹配,则他们提供了正确的密码。以明文形式存储密码不是一个好主意。
答案 1 :(得分:-1)
你的 while 条件是错误的。您可以为此使用 for 循环(使用计数器),或者您需要重建您的 while 循环。您必须将 if 条件放在 While 循环中,不要将它们分开。 https://www.w3schools.com/cs/cs_while_loop.asp。使用 while 循环是实现无限的好机会。所以我一直在使用 For 循环。