skip to Main Content

When I use StreamReader` for some reason the file I use isn’t read. can I get any help?

enter image description here

I tried deleting the file and putting it in again but it didn’t work

3

Answers


  1. line is initialized to "", so the while loop is never entered. The condition should be line != null, not line == null like you currently have.

    Login or Signup to reply.
  2. 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, or null if the end of the input stream is reached.

    Also this makes inner check if(line != null) obsolete.

    Login or Signup to reply.
  3. 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++; }
        ...
        }
        ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search