0

Inside a using I'm generating a Stream:

using (var generatedStream = GenerateStream(str))
{
    var streamContent = generatedStream;
}

GenerateStream(string s) looks like this:

private static Stream GenerateStream(string s)
{
    var stream = new MemoryStream();
    using (var writer = new StreamWriter(stream))
    {
        writer.Write(s);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }
}

When I get to assigning generatedStream to streamContent, more specifically, when I exit the using statement in GenerateStream, it says that stream is disposed. What am I doing wrong in making sure I dispose my writer?

UPDATE:

The solution posted in the linked question seems to be the way to go for this particular problem.

Khaine775
  • 2,715
  • 8
  • 22
  • 51
  • 1
    The problem is that inside `GenerateStream` you dispose `writer`, which in turn disposes `stream` because `StreamWriter` takes control of that underlying stream. I remember there have been ways to tell `StreamWriter` not to do that, but I just can't find them... – René Vogt May 07 '18 at 14:16
  • 2
    This might be helpful: https://stackoverflow.com/a/2666906/1009661 – tukaef May 07 '18 at 14:17
  • @RenéVogt that would be the linked duplicate post I believe – Rahul May 07 '18 at 14:17
  • @Rahul yep, that's it. In the other constructors I found that take a bool, that bool was used to indicate append- or overwrite mode...thatswhy I was confused. – René Vogt May 07 '18 at 14:18

2 Answers2

0

The using statement in your method GenerateStream() shouldn't be present

using (var writer = new StreamWriter(stream))
{
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

the using statement helps in disposing the stream already. It disposes at the end of the code block.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

Ziregbe Otee
  • 534
  • 3
  • 9