0

Had got this error in my program. Came across a few posts which kind of gave me the idea that this issue is probably due to file size. As far as my program is concerned, the observation I find is for small file sizes I do not get this error. For a relatively larger one this error crops up.

So this post kind of gave me the idea about how to replicate it.

I tried it below with another piece of code:

    var filePath = @"C:\tools\sample_extract.csv";
    var li = File.ReadLines(filePath);
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine("Loop Count: {0}", i);
        foreach (string k in li) ;
        Thread.Sleep(1000);
    }
    Console.WriteLine("end");
    Console.ReadLine();

However, I couldn't raise the exception.

Community
  • 1
  • 1
deostroll
  • 11,661
  • 21
  • 90
  • 161
  • 3
    _"Came across a few posts which kind of gave me the idea that this issue is probably due to file size"_ - no, it occurs when you try to read from a textreader whose underlying stream has been disposed. See http://stackoverflow.com/questions/2304243/bug-in-the-file-readlines-method-of-the-net-framework-4-0 – CodeCaster Dec 12 '13 at 10:37
  • show us code which gives you error – Guru Stron Dec 12 '13 at 10:38
  • @GuruStron its quite huge...in short I just call `File.ReadLines()` once, and use the `IEnumerable` it gives at various places through out the code...I keep calling the `GetEnumerator()` (on the same reference)... – deostroll Dec 12 '13 at 10:40
  • @deostroll if you want to try to simulate error with file size then you should create file, read it, if everything ok then append some data to it, reopen it and reread. – Guru Stron Dec 12 '13 at 10:46
  • 1
    @deostroll, if that is the case then @CodeCaster's link probably explains your error. The internal `TextReader` created by `ReadLines` is closed when you enumerate to the end of the file, which means that the `IEnumerable` is no longer re-usable. You need to call `File.ReadLines()` every time instead of re-using the `IEnumerable`. – odyss-jii Dec 12 '13 at 10:58
  • @odyss-jii if that's the case then the above code should give an error. – deostroll Dec 12 '13 at 11:33
  • That depends -- are you sure that it is actually executing the empty loop? What happens if you add a `Console.WriteLine(k)` inside the `foreach`? – odyss-jii Dec 12 '13 at 11:38
  • @deostroll have you tried to use `File.ReadAllLines` instead? And this behavior can be version dependent. Do you use same versions of `.Net` for your program and this test code? – Guru Stron Dec 12 '13 at 13:40
  • @GuruStron afaik that would get the entire lines in the file to memory...I don't recommend that. I need to make passes on a few lines in the file (like first 5) several times. I don't want to get the entire file into memory for that. – deostroll Dec 13 '13 at 04:06

0 Answers0