StreamReader ReadLine returns null when not EOF

2019-06-08 00:43发布

Having a strange problem that I've never encountered nor heard of happening. It seems that occasionally, the ReadLine() function of the StreamReader class will return NULL, as if it's at the end of the file, BUT it's not.

My log file indicates that everything is happening just as if it had actually reached the end of the file, but yet it's only processing part of it. There doesn't appear to be any consistency, because if I restart the process from scratch, the whole file is processed without incident.

Clearly, there is nothing funky in the file itself, or it would do this on the same line each time, plus it has happened with a few different files, and each time they are re-run, it works fine.

Anyone run across anything similar, or have any suggestions on what might be causing such a thing?

Thanks,

Andrew

Sample:

line = _readerStream.ReadLine();

if (null != line)
{
    eventRetVal = loadFileLineEvent(line);
}
else
{
    // do some housecleaning and log file completed
}

_readerStream is the stream which has been opened elsewhere.

loadFileLineEvent is a delegate that gets passed in which processes the line. This has its own error handling (with logging), so there's no issue in there.

The routine above (not shown in its entirety) has error handling around it also (with logging), which is not being triggered either.

It's getting to the "else" and logging that it reached the end of the file, but it's obvious from the number of records I got that it didn't.

1条回答
女痞
2楼-- · 2019-06-08 01:31

Have you tried a more traditional approach to reading the stream? This way your checking for the end of the stream before reading the next potentially empty/null line. Seems like your code should work, but with a possible null exception thrown for trying to read a line that doesn't exists(not sure if SR throws for that though).

 using (StreamReader SR = new StreamReader(OFD.FileName))
 {
     while (!SR.EndOfStream)
     {
         string CurrentLine = SR.ReadLine();
         var eventRetVal = loadFileLineEvent(CurrentLine);
     }
 }
查看更多
登录 后发表回答