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?

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked, thank you! Still im kind of interested, why didn't the code I presented work?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.