即使Log.txt文件包含我尝试登录的用户名和密码,以下STILL也无效。
这是我的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();
}
有什么想法吗?
答案 0 :(得分:6)
您的代码无效,因为只是查看字符串“log.txt”是否包含用户名实际上是否打开文件并检查内容。
无需使用StreamReader
/ StreamWriter
来阅读文件的文本。您只需打开文件,阅读内容,然后检查:
contents = File.ReadAllLines(@"C:\Path\To\File\log.txt");
if(contents.Contains(Username.Text))
// ...
我真诚地希望您不要指望此系统安全性最低。将所有用户名/密码组合存储在纯文本文件中非常糟糕。任何人都可以打开它,阅读它,并查看文件中的每个组合。此外,我所要做的就是猜测文件中的一些随机字符串。我最好的选择是猜一封信。我将有1/26的机会在你的文件中存在该角色,我将被授予访问权限。
答案 1 :(得分:1)
您的代码没有按照您的想法执行。
if ("log.txt".Contains(Username.Text))
这只是检查"log.txt"
(作为字符串,而不是文件)是否包含用户名字段中包含的文本。
假设您只是尝试检查用户名是否存在,您可以执行以下操作:
using System.Linq;
// ...
var usernames = File.ReadAllLines(@"C:\log.txt");
if (usernames.Contains("Username : " + Username.Text)) {
// Username exists
请注意,上面的代码并不关心任何类型的密码,并且无论如何都无法生产。您根本不应该使用文本文件来存储凭据,并且应该考虑使用数据库,并使用适当的散列和密码等。在尝试将其放入您的应用程序之前,我会考虑更多地了解这种做法,因为这是非常基本的。
与您的问题相关的第一个指示应该是您实际上并未在任何地方使用 StreamReader
或StreamWriter
。
答案 2 :(得分:0)
if("log.txt".Contains(Username.Text)
这是检查实际字符串“log.txt”是否包含用户名,并且不会接近任何文件。
答案 3 :(得分:0)
您正在使用“Log.txt”作为字符串。您需要搜索文件中的实际值。