Can I put StreamReaders in a list? Or any other way to read a lot of text files at once?

46 views Asked by At

I have a lot of text files and want to read them all by once, how do I do this? This is my code till now:

List<StreamReader> lijst = new List<StreamReader>();
using (StreamReader qwe = new StreamReader("C:\\123.txt"))
using (StreamReader qwer = new StreamReader("C:\\1234.txt"))
lijst.Add(qwe);
lijst.Add(qwer);

But I get an ObjectDisposedException(Cannot read from a closed TextReader.) when doing this:

lijst[0].Readline();

Any idea how to fix this? Thansk in advance

2

There are 2 answers

4
dotnetom On BEST ANSWER

You are not using curly braces, so you cannot see where the object is disposed. You code is identical to this code:

List<StreamReader> lijst = new List<StreamReader>();
using (StreamReader qwe = new StreamReader("C:\\123.txt"))
{
    using (StreamReader qwer = new StreamReader("C:\\1234.txt"))
    {
        lijst.Add(qwe);
    }
}
lijst.Add(qwer);

This means that when you get to the last line of this code your stream readers are already disposed. In your case you should not use using, but you need to make sure to dispose the stream readers afterwards:

try
{
    List<StreamReader> lijst = new List<StreamReader>();
    StreamReader qwe = new StreamReader("C:\\123.txt");
    StreamReader qwer = new StreamReader("C:\\1234.txt");
    lijst.Add(qwe);
    lijst.Add(qwer);

    // Use the stream readers
}
// you can use or not use catch here, it depends
finally
{
    qwe.Dispose();
    qwer.Dispose();
}
3
GolezTrol On

The using statement also defines the scope of the variable. As soon as the statement block in each using statement finishes, qwe and qwer go out of scope.

To solve this, don't use using:

StreamReader qwe = new StreamReader("C:\\123.txt");
lijst.Add(qwe);

or just

lijst.Add(new StreamReader("C:\\123.txt"));

Note though, that the file will immediately be opened, and will only be closed when the list and all its readers goes out of scope (or if you explicitly close the readers). Anyway, it's not very efficient, and you shouldn't do this with a list of hundreds of files. A better solution would be to store a list of filesnames, and keeps the actual files open as short as possible, and as few as possible at a time.