The last time through the loop, the code first checks for null
, but finds a value. It then reads from the file and returns null
into the linha
variable. Next it tries to split the null
string, which causes your error. Finally (assuming you catch the exception) it will go back to the beginning of the loop
and check for null
again. This time it will find null
and quit the loop.
To fix this, you need to read from the file before you check for null. You can use this pattern:
string login = @"utilizadores.txt";
using (StreamReader sr = File.OpenText(login))
{
string linha = sr.ReadLine();
while(linha != null)
{
string[] vetorUtilizadores = linha.Split(';');
linha = sr.ReadLine();
}
}
or this pattern:
string linha = "";
string login = @"utilizadores.txt";
using (StreamReader sr = File.OpenText(login))
{
while((linha = sr.ReadLine()) != null)
{
string[] vetorUtilizadores = linha.Split(';');
}
}
Note the addition of using
blocks around the StreamReader. That really is important.
You can also use this pattern:
string login = @"utilizadores.txt";
var lines = File.ReadLines(login).Select(linha => linha.Split(';'));
That last one might eventually let you write code like this:
bool validAccount = lines.Any(x => x[0] == username && x[1] == password);
What's really nice here is if your user is the first person in the list, that code only ever reads the first line from the file. Of course, if they are not in the list at all it will still need to read through the entire file, but at least you have a chance to save on some disk I/O.
And of course I'm assuming this is student code. No one really keeps a username/password list in a plain text file. Right?