0

I'm using C# code analysis and got the following error:

Object 'respStream' can be disposed more than once in method 'QRadarPublisher.AnalyzeResponse(HttpWebResponse)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 116

And this is the code:

using (Stream respStream = webResponse.GetResponseStream())
{   
    using (var tStreamReader = new StreamReader(respStream))
    {

        try
        {
            //My Code
        }
        catch (Exception ex)
        {
            //My Code
        }
     }
}//The error is for this brace

How can I solve the error?

Luiso
  • 4,173
  • 2
  • 37
  • 60
CSharpBeginner
  • 601
  • 2
  • 7
  • 22
  • 1
    It is because calling `Dispose` on the `StreamReader` disposes the stream as well. , see http://stackoverflow.com/questions/1065168/does-disposing-streamreader-close-the-stream – Peter Bons Feb 05 '17 at 19:14
  • Merge this two using in single one : `using (var tStreamReader = new StreamReader(webResponse.GetResponseStream()))`. – Kalten Feb 05 '17 at 19:14

1 Answers1

2

You can always get rid of the first 'using' block:

        Stream respStream = null;
        try
        {
            respStream = webResponse.GetResponseStream();
            using(var tStreamReader = new StreamReader(respStream))
            {
    // If this line is reached you don't need to call Dispose manually on respStream
    // so you set it to null

               respStream = null; 
               try
               {
                 //My Code
               }
               catch(Exception ex)
               {
                //My Code
               }
            }
        }
        finally
        {
// if respStream is not null then the using block did not dispose it
// so it needs to be done manually:
           if(null != respStream)
               respStream.Dispose();
        }
Andy
  • 3,631
  • 2
  • 23
  • 32