check for null and end of stream in same statement

和自甴很熟 提交于 2019-12-11 09:15:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!