1

I'm really annoyed when "using" block tampered my pre-created object. I have this piece of code

class Asset {
    public Stream FileStream { get; set; }

    public Asset(string fileName) {
        FileStream = ...open a file stream...;
    }
}

// Somewhere else
Asset asset = new Asset("file.txt");
using (var reader = new StreamReader(asset.FileStream)) {
    //blah blah blah
}

// Somewhere else else
using (var reader2 = new StreamReader(asset.FileStream))

=> throws this exception:

System.ArgumentException: Stream was not readable.

Debugging step-by-step in Visual Studio helped me know that asset.FileStream has been disposed after the first "using" block.

Please help me to save his life :(( How can I create a clone stream from a stream?

hirikarate
  • 3,055
  • 4
  • 21
  • 27
  • 2
    I think the simple answer is don't dispose the stream before you are through with it... when you use a using block it will Dispose the Reader and in turn Dispose the stream. – Glenn Ferrie Mar 08 '12 at 05:00

1 Answers1

2

I agree that the fact that readers close the underlying stream is dumb. The approach outlined in this article is to create a decorator class that wraps the Stream and has a no-op for the Close and Dispose methods. It's probably not worth the overhead, though, so you should consider just not using using for these readers.

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • Or, if the two using blocks are in the same method, you could move the second inside the first. – phoog Mar 08 '12 at 05:53