简体   繁体   English

C#Windows表单登录程序

[英]C# Windows Form Login Program

Im looking to create a simple windows login form i have the files loading form a text file on my c drive, but when i compare the string the the list i have create and its not working correctly this is my code 我正在寻找创建一个简单的Windows登录表单,我将文件加载到C驱动器上的一个文本文件中,但是当我比较字符串时,我创建的列表及其无法正常工作,这是我的代码

    private void button1_Click(object sender, EventArgs e)
    {
        const string f = "C:/Users.txt";

        List<string> lines = new List<string>();

        string userNameInput = Convert.ToString(userBox);

        using (StreamReader r = new StreamReader(f))
        {

            string line;
            while ((line = r.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }
        for (int i = 0; i < lines.Count; i++)
        {
            MessageBox.Show(lines[i]);
            MessageBox.Show(userNameInput);
            if (lines[i] == userNameInput)
            {
                MessageBox.Show("correct");
            }
            else
            {
                MessageBox.Show("Not Correct");
            }

        }
    }
}

} }

You can do as below 你可以做如下

if (File.ReadAllLines("C:/Users.txt").Select(x=>x.Trim()).Contains(userBox.Text.Trim()))
{
    MessageBox.Show("correct");
}
else
{
    MessageBox.Show("Not Correct");
}

What it does is read all lines from your file and trim each line and compare with input text. 它的作用是从文件中读取所有行并修剪每行并与输入文本进行比较。 if there is matching line you will receive message as correct 如果有匹配的行,您将收到正确的消息

You could simply a bit with: 您可以简单地使用:

        const string f = @"C:\Users.txt";
        string[] lines = System.IO.File.ReadAllLines(f);
        if (Array.IndexOf(lines, userBox.Text) != -1)
        {
            MessageBox.Show("correct");
        }
        else
        {
            MessageBox.Show("Not Correct");
        }

Why use this? 为什么要使用这个?

string userNameInput = Convert.ToString(userBox);

This could be used and is easier to get the text of the textBox by its self. 可以使用它,并且更容易通过自身获取textBox的文本。

string userNameInput = userBox.text;

And this should should help with what you need. 并且这应该可以帮助您满足需求。

const string f = "C:/Users.txt";
string file = System.IO.File.ReadAllText(f);

string[] strings = Regex.Split(file.TrimEnd(), @"\r\n");

foreach (String str in strings)
{
    // Do something with the string. Each string comes in one at a time.
    // So this will be run like for but is simple, and easy for one object.
    // str = the string of the line.
    // I shall let you learn the rest it is fairly easy. here is one tip
    lines.Add(str);
}
// So something with lines list

I hope I had helped! 我希望我有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM