[英]How do I read one line for a .txt file in c#?
我正在嘗試創建具有登錄功能和注冊功能的密碼數據庫。 通過將名稱,姓氏,電子郵件和密碼保存到一個.txt文件中,我可以使用注冊功能。但是,我無法使程序讀取一行,然后檢查用戶輸入的密碼是否與該密碼匹配。 .txt文件。 到目前為止,這是我正在使用的工具。
//reading from file
int counter = 0;
private void Enter_btn_Click(object sender, EventArgs e)
{
// makes a new file called password.txt
StreamReader sr = new StreamReader("password.txt");
string Line = "";
//this reads all lines in the .txt file
while ((Line = sr.ReadLine())!=null)
{
//loops through each line.
counter++;
break;
}
}
我希望while循環只看一行,然后輸入用戶名,然后再檢查另一行並驗證用戶名是否正確。
counter++;
break;
我希望它經過第一行然后中斷並到達第一行。 我正在使用Form Application在Visual Studio中工作。
您可能需要更改插入數據的方式。
嘗試在值之間插入制表符(\\ t),並以(\\ n)結尾記錄,以便您可以讀取整個文件並使用String.Split('\\ n'),這將為您提供單獨的記錄,並再次按String.Split('\\ t')獲取用戶名和密碼組合。
然后,您可以使用邏輯來驗證憑據
您可以在不使用循環的情況下使用if語句,但必須手動執行。
例如:
//reading from file
int counter = 0;
private void Enter_btn_Click(object sender, EventArgs e)
{
// makes a new file called password.txt
StreamReader sr = new StreamReader("password.txt");
string usr = "";
string pass = "";
pass = sr.ReadLine();
if(pass != null)
{
//You get the password here now you can do the logic
}
else
{
//There is no line should throw an exception for instance
}
//Now lets get the username
usr = sr.ReadLine();
if(usr != null)
{
//You get the usr here
}
else
{
//There is no 2nd line should throw an exception for instance
}
}
您可以執行以下操作:
StreamReader sr = new StreamReader("password.txt");
string user;
while((user = sr.ReadLine()) != null)
{
string password;
if ((password = sr.ReadLine()) == null) {
// TODO: Throw some exception for example Illegal State.
}
if (string.Equals(user, #user)) {
if (string.Equals(password , #password)) {
sr.Close();
// SUCCESS
} else {
// WRONG PASSWORD
}
}
}
sr.Close();
// WRONG USER
您可以閱讀第一行,而不是逐行進行遍歷。
int counter = 0;
private void Enter_btn_Click(object sender, EventArgs e)
{
// makes a new file called password.txt
StreamReader sr = new StreamReader("password.txt");
string Line = sr.ReadLine();
//this reads all chars in the line
foreach (var ch in Line)
{
//loops through each char.
counter++;
break;
}
}
如果只需要長度,則可以使用Line.length
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.