while ((line = sr.ReadLine()) != null && !sr.EndOfStream)

This does not work. It literally keeps looping and I get an exception because "line" is null, and the EndofStream has been reached. Any idea?

有帮助吗?

解决方案 2

If you put both checking together, code will escape looping even if ReadLine() is null before reaching EndOfStream. Following is a breakdown version but will go through the whole stream.

while (!sr.EndOfStream)
{
   if ((line = sr.ReadLine()) != null)
   {
      //do your work here
   }
}

其他提示

You can simply use the following, ReadLine will return null when end of file is reached, so checking for EndOfStream is not necessary.

while ((line = streamReader.ReadLine()) != null)
{
    // do stuff
}

MSDN:

Return Value Type: System.String The next line from the input stream, or null if the end of the input stream is reached.

Use only this part

while ((line = sr.ReadLine()) != null)
{
   // your code
}

In case you'd like to skip the empty lines: a line in a text file cannot be Null, null in this case means when there is no more lines. So if you wanna check if a line is empty the (line = sr.ReadLine()) != null won't work. You can do it this way, although there are many other ways:

while ((line = sr.ReadLine()) != null)
    if (!line.Trim().Equals("")) {
        // Do something 
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top