我有一個登錄頁面,我試圖讓窗體讀取文本框+「.txt」中的內容,以便它打開相應的頁面。我已經成功地第一次檢查,看是否存在但隨後的第二部分不工作 - 錯誤信息中給出的路徑是不支持在文件路徑+出現名爲「.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);
}
}
}
}
嘗試使用[Path.Combine(https://msdn.microsoft.com/en-us/library/dd784047%28v=vs.110%29.aspx?f=255&MSPPError= -2147217396)創建文件名。並確保用戶名中沒有特殊字符。 –
我認爲第二次在文本文件中沒有數據,或者在txt文件中沒有分號(;) –
這些文本文件與可執行文件位於同一文件夾中嗎?您的代碼目前正在編寫的方式,這是它的唯一工作方式。請記住,如果你通過visual studio的調試器運行它,執行的文件夾將是bin/Debug或bin/Release(取決於你正在構建的配置),所以它會在那裏查找txt文件。 –