1

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.

Community
  • 1
  • 1
tnw
  • 13,521
  • 15
  • 70
  • 111
  • Yes your question is vague. You can improve it by adding some code – Steve Apr 18 '13 at 19:40
  • Without any code, hard to say anything – I4V Apr 18 '13 at 19:41
  • @Steve Added some code and details – tnw Apr 18 '13 at 19:44
  • 1
    @tnw Yes i see the edit. But I see no code to talk about. `blah blah`s and `....`s hide the bug. – I4V Apr 18 '13 at 19:50
  • 5
    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 – Thomas Levesque Apr 18 '13 at 19:52
  • 1
    @ThomasLevesque - you should put "externalStreamProvider is returning the same stream instance every time" as answer – Alexei Levenkov Apr 18 '13 at 19:54
  • I have to disagree with I4V and Steve and agree with Thomas. Nothing that could cause the bug is hidden in `.....` or `blah blah`. When the exception is raised on `stream.Position` it is a brand new instance of `Stream` on the 2nd iteration. – tnw Apr 18 '13 at 19:56
  • I agree with Thomas too: It's likely that the stream provider is responsible for the lifetime of the stream, not the caller. – Matthew Watson Apr 18 '13 at 20:02

1 Answers1

1

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...

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758