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 != "");
Here is one classic block of code where stream and stream reader are used. They both are disposable.
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 .
StreamReader. ReadLine() method reads a line of characters from the current stream and returns the data as a string.
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 ...
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With