Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamReader.ReadLine will hang in an infinite loop

I have a simple program to read a file using the StreamReader and process it line by line. But the file I am reading may sometimes locate in a network folder. I came across while doing some testing with such a file, that if the network connection lost at some point while I am reading, it'll stay in the same line again and again looping in an infinite loop by resulting the same line as the result from stream.ReadLine().

Is there a way I can find when the fileHandle is not available from the stream itself? I was expecting a FileNotAvailableException kind of an exception would fire when the filehandle is lost from the StreamReader.

Here's my code snippet...

        string file = @"Z://1601120903.csv"; //Network file
        string line;
        StringBuilder stb = new StringBuilder();      
        StreamReader stream = new StreamReader(file, Encoding.UTF8, true, 1048576);
        do
        {
            line = stream.ReadLine();
            // Do some work here
        } while (line != "");
like image 643
Asanka Avatar asked Feb 10 '16 15:02

Asanka


People also ask

Is StreamReader disposable?

Here is one classic block of code where stream and stream reader are used. They both are disposable.

What does StreamReader mean?

A StreamReader is a TextReader which means it is a Stream wrapper. A TextReader will convert (or encode) Text data (string or char) to byte[] and write them down to the underlying Stream .

What does StreamReader return?

StreamReader. ReadLine() method reads a line of characters from the current stream and returns the data as a string.

How do I reset StreamReader?

There is no public methods to reset this encoding and preamble state so the safest thing to do if you need to "rewind" a stream reader is to seek the underlying stream to the beginning (or set position) as shown and create a new StreamReader , just calling DiscardBufferedData() on the StreamReader will not be ...


1 Answers

Compare with null not with empty string:

https://msdn.microsoft.com/en-us/library/system.io.streamreader.readline(v=vs.110).aspx

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

    do
    {
        line = stream.ReadLine();
        // Do some work here
    } while (line != null);

A better approach, however, is to let .Net do the work (line by line file reading) for you and drop all readers:

  foreach (String line in File.ReadLines(file)) {
    // Do some work here
  }
like image 54
Dmitry Bychenko Avatar answered Oct 05 '22 06:10

Dmitry Bychenko