我有一个登录页面,我正在尝试让表单读取文本框中的内容+“。txt”,以便打开相应的页面。我已经设法首先检查它是否存在,但第二部分不起作用 - 不支持给出路径的错误消息出现在filePath +“。txt”
见下面的代码:
public bool check_user(string pUsername)
{
//checks first to see if user exists
using (StreamReader sr = new StreamReader(pUsername + ".txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
//read first bit of data from text file eg username, data split by ";"
string[] data = line.Split(';');
if (data[0] == pUsername)
{
MessageBox.Show("User found");
return true;
}
}
MessageBox.Show("User not found, try again");
return false;
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
//Read from file
if (check_user(txtUsername.Text.Trim()))
{
string filePath = txtUsername + ".txt";
using (StreamReader sr = new StreamReader(filePath + ".txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
//read first bit of data from text file eg username, data split by ";"
string[] data = line.Split(';');
if (data[0] == txtUsername.Text.Trim())
{
break;
}
}
// read second bit of data from text file eg password, data split by ";"
string[] user = line.Split(';');
if (user[1] == txtPassword.Text.Trim())
{
// checks access levels by viewing the third part of data and corresponds to which form to open
if (user[2] == "employee")
{
EmployeeForm frm = new EmployeeForm();
frm.Show();
}
else if (user[2] == "admin")
{
AdminForm frm = new AdminForm();
frm.Show();
}
}
else
{
MessageBox.Show("Login not successful, try again", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
答案 0 :(得分:0)
首先你这样做:
check_user(txtUsername.Text.Trim())
表示txtUsername
是某种具有Text
属性的控件。下面两行:
string filePath = txtUsername + ".txt";
这相当于
string filePath = txtUsername.ToString() + ".txt";
因为txtUsername
不是字符串,而是某些具有Text
属性的控件 - 最终会出现无效路径。将其更改为:
string filePath = txtUsername.Text.Trim() + ".txt";