Reputation: 3432
On my service I am trying to create and return a MemoryStream
like this:
// Write data.
MemoryStream memoryStream = new MemoryStream();
using (StreamWriter txtwriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8))
{
string tempString = "Test";
txtwriter.Write(tempString);
txtwriter.WriteLine();
// End response.
memoryStream.Position = 0L;
response.ReportMemoryStream = memoryStream;
response.Length = memoryStream.Length;
return response;
}
Note: having the End response
part outside the using
statement causes a Cannot access a closed stream error
.
My response
is a simple DataContract
. When I try to read this data in my client doing something like this:
// Write stream.
if (remoteReport.ReportMemoryStream != null)
{
remoteReport.ReportMemoryStream.WriteTo(Response.OutputStream);
}
I get again the same error about the stream being closed.
How can I fix this issue and why is my stream closing even though I'm not explicitly doing so?
Upvotes: 1
Views: 601
Reputation: 3726
You'll need to flush your StreamWriter
instance, so it writes to the MemoryStream
instance -
txtwriter.Flush();
Then you'll need to remove the using
block, so the txtwriter
doesn't by default destroyes the memoryStream
.
Upvotes: 1
Reputation: 7228
replace:
response.ReportMemoryStream = memoryStream;
with
memoryStream.CopyTo(response.ReportMemoryStream);
now you are using reference type I think, and your using
statment is just disposing stream you are using.
Upvotes: 1