0

即使 Log.txt 文件包含我尝试登录的用户名和密码,以下仍然无法正常工作。

这是我的 REMADE 登录代码:

public void button1_Click(object sender, EventArgs e)
    {
        bool loggedin = false;
        Form2 form2 = new Form2();
        Form1 form1 = new Form1();
        var contents = File.ReadAllLines(@"C:\log.txt");
        if (contents.Contains(Username.Text))
                {
                    loggedin = true;
                    MessageBox.Show("Login sucessfully", "Program", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    form1.Hide();
                    form2.Show();
                }

                else
                {
                    if (loggedin == false)
                    {


                        MessageBox.Show("Invalid username or password.", "Program", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

        }

这是我的注册码:

    {
        using (System.IO.StreamWriter writer = new System.IO.StreamWriter("C:\\log.txt", true))
        {
            writer.WriteLine("\r" + "Username : " + textBox1.Text);
            writer.WriteLine("Password : " + textBox2.Text);
            writer.WriteLine("Age : " + textBox4.Text);
        }

        Form5 form5 = new Form5();
        Form1 form1 = new Form1();
        form1.Show();
        this.Hide();
    }

有任何想法吗?

4

4 回答 4

6
  1. 您的代码不起作用,因为仅仅查看字符串“log.txt”是否包含用户名实际上并没有打开文件并检查内容。

  2. 无需使用StreamReader/StreamWriter来读取文件的文本。您只需要打开文件,阅读内容,然后检查这些内容:

    contents = File.ReadAllLines(@"C:\Path\To\File\log.txt");
    if(contents.Contains(Username.Text))
    // ...
    
  3. 我真诚地希望你不要指望这个系统是安全的。将所有用户名/密码组合存储在纯文本文件中是很糟糕的。任何人都可以打开它,阅读它,并查看文件中的每一个组合。此外,我所要做的就是猜测文件中的一些随机字符串。我最好的选择是猜一个字母。我将有 1/26 的机会该角色存在于您的文件中,并且我将被授予访问权限。

于 2013-05-20T15:24:48.127 回答
1

Your code is not doing what you think it is doing.

if ("log.txt".Contains(Username.Text))

This is simply checking if "log.txt" (as a string, not a file) contains the text contained within the username field.

Assuming that you're trying to check only if a username exists, you could do something like this:

using System.Linq;

// ...

var usernames = File.ReadAllLines(@"C:\log.txt");
if (usernames.Contains("Username : " + Username.Text)) {
    // Username exists

Note that the code above doesn't take any care for a password of any type, and is certainly not production-ready in anyway. You shouldn't be using a text file to store your credentials at all and should consider using a database, with appropriate hashing and whatnot for passwords. I'd consider learning a bit more about this practice before trying to put it into your application as this is fairly basic.

The first indication relating to your question should be that you're not actually using StreamReader or StreamWriter anywhere.

于 2013-05-20T15:27:15.507 回答
0
if("log.txt".Contains(Username.Text)

这是检查实际字符串“log.txt”是否包含用户名,并且不靠近任何文件。

于 2013-05-20T15:25:21.213 回答
0

您正在使用“Log.txt”作为字符串。您需要在文件中搜索实际值。

于 2013-05-20T15:25:50.533 回答