hirikarate
hirikarate

Reputation: 3295

Pre-created Stream and "using" block

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?

Upvotes: 1

Views: 283

Answers (1)

Jacob
Jacob

Reputation: 78880

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.

Upvotes: 2

Related Questions