1

I have tired using statement after going through the links in stackoverflow but still couldnt figure the exact solution.

 using (MemoryStream stream = new MemoryStream(textAsBytes))
            {
                using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StreamContent(stream)
                })
                {
                    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "main-theme.scss"
                    };
                    httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");

                    ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
                    return responseMessageResult;
                }
            }

getting the following error

CA2000 In method 'GetStyleSheet()', object 'new HttpResponseMessage()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new HttpResponseMessage()' before all references to it are out of scope.

Yashwanth Kata
  • 817
  • 8
  • 21

1 Answers1

0

The problem is that when creating the HttpResponseMessage you use a property initializer in addition to the constructor:

using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
  Content = new StreamContent(stream)
})
{
  // ...
}

This leads to a code similar to the following is generated:

var httpRepsonseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(stream);
try
{
   // ...
}
finally
{
  httpResponseMessage.Dispose();
}

As you can see, httpResponseMessage will not be disposed if something goes wrong when creating the StreamContent and assigning it.

In order to solve this, move the assignment into the using block:

using (HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK))
{
  httpResponseMessage.Content = new StreamContent(stream);
  // ...
}

This way, the disposal takes place even if there is a problem when assigning the content.

Markus
  • 20,838
  • 4
  • 31
  • 55