I’m fairly close I believe but my stream is either null or its been disposed. Here is the sample code.
var ms = new MemoryStream();
using (var sw = new StreamWriter(ms))
{
using (var tw = new HtmlTextWriter(sw))
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, null);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, tw);
ms.Position = 0;
return ms;
}
}
the calling code results in an objectDisposedException because the stream is disposed. If I move the return outside of the using, the result is null. What am I doing wrong here? Any ideas how I can this to work correctly?
To use a class in a
usingblock, that class must implementIDisposable. When the block ends, it invokesIDisposable.Dispose()which disposes your Stream. This is a good practice, but if you want the stream, either remove theusingor put the return inside it. I would go with the second option.