C#Windows表单登录程序

时间:2013-07-05 03:17:25

标签: c#

我希望创建一个简单的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");
            }

        }
    }
}

}

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作

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

它的作用是读取文件中的所有行并修剪每一行并与输入文本进行比较。如果有匹配的行,您将收到正确的消息

答案 1 :(得分:1)

你可以简单地说:

        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");
        }

答案 2 :(得分:1)

为什么要用这个?

string userNameInput = Convert.ToString(userBox);

这可以使用,并且更容易通过它自己获取textBox的文本。

string userNameInput = userBox.text;

这应该有助于你需要的东西。

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

我希望我有所帮助!