7

I tried using the answer from here, but it did not work. I have the following code:

public ActionResult ShowImage() 
{
    using (FileStream stream = new FileStream(Path.Combine(Server.MapPath("/App_Data/UserUpload/asd.png")), FileMode.Open))
    {
        FileStreamResult result = new FileStreamResult(stream, "image/png");
        result.FileDownloadName = "asd.png";
        return result;
    }

}

When I open up the page I get an error which says: "Cannot access a closed file.". I did some googling on the error, but I only found this error associated with uploading. What causes the issue here?

Community
  • 1
  • 1
Esa
  • 1,636
  • 3
  • 19
  • 23

1 Answers1

9

Try like this:

public ActionResult ShowImage() 
{
    var file = Server.MapPath("~/App_Data/UserUpload/asd.png");
    return File(file, "image/png", Path.GetFileName(file));
}

or if you want a separate filename:

public ActionResult ShowImage() 
{
    var path = Server.MapPath("~/App_Data/UserUpload");
    var file = "asd.png";
    var fullPath = Path.Combine(path, file);
    return File(fullPath, "image/png", file);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This worked, thank you! Still im kind of interested, why didn't the code I presented work? – Esa Jun 03 '11 at 10:20
  • 1
    @Esa, in the code you presented you have wrapped the FileStream into a `using` clause meaning that this stream will be disposed before the controller action returns. But the action result will be executed much later in the MVC pipeline and when it tries to use the Stream you have passed to the `FileStreamResult` it will be closed. – Darin Dimitrov Jun 03 '11 at 10:56