When I use StreamReader` for some reason the file I use isn't read. can I get any help?
I tried deleting the file and putting it in again but it didn't work
CodePudding user response:
line
is initialized to ""
, so the while
loop is never entered. The condition should be line != null
, not line == null
like you currently have.
CodePudding user response:
Your while
loop condition is not correct it should be while(line != null)
, first of all line
is initialized to empty string (""
) so with current code the loop is never entered, secondary line = b.ReadLine();
should not be null
until the file ends - from the StreamReader.ReadLine
docs:
Returns
String
The next line from the input stream, ornull
if the end of the input stream is reached.
Also this makes inner check if(line != null)
obsolete.
CodePudding user response:
Your while
is not correct; just have a look:
...
string line = "";
// line is NOT null (it's empty) that's why
// while will not enter at all
while (line == null)
{
...
}
Let's change while
into for
, let pesky line
(which is declared out of loop, is check in while
, in if
etc.) be a loop variable:
// Wrap IDisposable into using; do not Close them expplicitly
using (StreamReader b = new StreamReader("students.txt"))
{
...
for (string line = b.ReadLine(); line != null; line = b.ReadLine())
{
if (line == "2") { num2 ; }
...
}
...
}