假设下面的ReadUser方法正在读取文本文件中的用户和密码。问题是,在读取前两行后,它不会读取文本文件的其余部分。如何解决这个问题?
*编辑:如何读取文本文件中的前2行,然后再读取另外2行?
public override void ReadUser()
{
user = base.UserID;
password = base.Password;
using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt", FileMode.Open)))
{
user1 = sr.ReadLine();
password1 = sr.ReadLine();
sr.Close();
if (user == user1 && password == password1)
{
Console.WriteLine("Login Successfull");
}
else
{
Console.WriteLine("Login Failed");
}
}
}
答案 0 :(得分:1)
简单的基本逻辑
int currentLine = 0;
//no need use close method with using
using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt", FileMode.Open)))
{
string line;
while ((line = sr.ReadLine()) != null)
{
switch (++currentLine)
{
case 1: user1 = line; break;
case 2: password1 = line; break;
case 3: otherVariable = line; break;
case 4: yetAnotherVariable = line; break;
......
}
//rest of your logic
}
}
但是,如果出于某种原因需要将所有字符串存储在数组中,则最好只使用File.ReadAllLines();