问题
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?
回答1:
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
}
}
回答2:
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.
回答3:
Use only this part
while ((line = sr.ReadLine()) != null)
{
// your code
}
回答4:
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
}
}
来源:https://stackoverflow.com/questions/20763353/check-for-null-and-end-of-stream-in-same-statement