首页 > 解决方案 > 我搞砸了一个“While”循环......我可以修复它吗?

问题描述

我试着做一个while循环,我知道问题所在,我只是不知道如何解决它。我使用的 int 从不更新,使代码无用......我使用 Visual Studio,windows fom 应用程序,如果这改变了一些东西......对不起,长度,但我不知道问题出在哪里。(输入 1 和 2 是文本框...)我使用的文本文件如下所示: 用户名:换行 (服装文本)换行 密码:换行 (服装文本)换行 用户名:换行 ...

这是代码:

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)

    }
}

标签: c#filewhile-loop

解决方案


这可以大大简化。用户名和密码在交替行上,因此需要在循环内声明。您还可以使用 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!");
    }
}

当然......你应该记住,这根本不安全。在现实世界中,密码应该是一种散列和加盐的方式。然后,当用户想要进行身份验证时,您再次散列密码并将其与存储的值进行比较。如果它们匹配,那么他们提供了正确的密码。以明文形式存储密码不是一个好主意。


推荐阅读