Search code examples
c#streamnancy

NancyFx: Are streams disposed when using StreamResponse()?


Are streams disposed in NancyFx when using StreamResponse()?

Using a streamWriter to write to the stream, I can't dispose of it without closing the stream I want to send out. And the way I see it, I can't dispose of the stream manually either since I effectively left the method at the return.

This code works:

// Open a stream and write to it with streamReader
Stream memStream = new MemoryStream();
StreamWriter memWriter = new StreamWriter(memStream, Encoding.UTF8);
memWriter.Write(someStringText);
memWriter.Flush();
memStream.Position = 0;

// Add stream to the respose which should get downloaded
var response = new StreamResponse(() => memStream, MimeTypes.GetMimeType(contentType));
return response.AsAttachment(someFileName);

Do I need to worry about the stream lingering on until the garbage collector comes along or do it get disposed correctly by the StreamResponse?


Solution

  • According to StreamResponse.cs, StreamResponse.Dispose() disposes of the stream returned by the Func<Stream>, and Nancy handles disposing the Response at the end of the NancyContext.

    As for disposing of StreamWriter without affecting the underlying stream, see this answer.