1

The below code is working perfect. It serves the specified image.

  public HttpResponseMessage Get(string id)     
  {
      string fileName = string.Format("{0}.png", id);
      FileStream fileStream = File.Open(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + fileName), FileMode.Open);
      HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
      response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
      response.Content.Headers.ContentLength = fileStream.Length;
      return response;
  }

Just to release the resource that I acquired to read the image file I have modified the code as follows.

public HttpResponseMessage Get(string id)     
{
   string fileName = string.Format("{0}.png", id);
   using (FileStream fileStream = File.Open(System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + fileName), FileMode.Open))
       {
            HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
            response.Content.Headers.ContentLength = fileStream.Length;
            return response;
        }
}

I am getting the error "Error while copying content to a stream". Yes. I am closing the resource before it is streamed.

But the question is how to serve the image and still close the unhandled resource? Asp.Net Web API 2 and above. Thank you for your thoughts.

svick
  • 236,525
  • 50
  • 385
  • 514
Ganesha K
  • 37
  • 4
  • Look into using `StreamContent` and adding a `MediaTypeHeaderValue` to the response headers – boosts Feb 04 '15 at 01:01

1 Answers1

1

You don't need to worry about releasing FileStream object. It will closed by lower layers of Web API once response is complete. Code mentioned in your first snippet is fine.

Sameer Azazi
  • 1,503
  • 10
  • 16
  • Do you any documentation to substantiate your statement? I can't convince my colleagues based on this justification. – Ganesha K Feb 04 '15 at 18:30
  • @GaneshaK I did not have any particular MSDN url for this topic. But I have answered you based on my experience of serving number of file objects through Web API. You can also refer [this question](http://stackoverflow.com/questions/3084366/how-do-i-dispose-my-filestream-when-implementing-a-file-download-in-asp-net/3086291#3086291) for further details – Sameer Azazi Feb 06 '15 at 05:15