tnw
tnw

Reputation: 13877

Stream - Cannot access a closed Stream

Small issue I'm having with a Stream, I'm getting the exception in the title.

I have it inside a using statement, which is inside a loop, and most posts I've seen just say to remove the using statement and "renew" it: Cannot access a closed Stream of a memoryStream, how to reopen?

The exception happens on the second iteration of the loop. I have tried removing the using statement with no effect.

Here's the general idea:

for (blah blah blah) 
{
    using (Stream strm = externalStreamProvider.GetStream(some params)
    { 
        if (stream.Position != 0) //exception is here on 2nd iteration
            ...........
    }
}

However, I am using Stream, which is abstract, so I cannot recreate it like myStream = new Stream().

I am using an external Stream provider, so I cannot change how the Stream is fetched.

Any ideas on how to fix this issue?

I apologize for any vagueness, please let me know if something is unclear.

Upvotes: 1

Views: 632

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292355

It seems like externalStreamProvider is returning the same stream instance every time... and since you closed it in the first iteration, it fails in the second.

If you expect to be working with the same stream in every iteration, you should get the stream outside the loop:

using (Stream strm = externalStreamProvider.GetStream(some params)
{
    for (blah blah blah) 
    { 
        if (stream.Position != 0)
            ...........
    }
}

EDIT: just saw this comment:

When the exception is raised on stream.Position it is a brand new instance of Stream on the 2nd iteration

In this case, the only explanation is that externalStreamProvider is returning a stream that is already closed; but then the problem is not in the code you posted...

Upvotes: 1

Related Questions