CSharpBeginner CSharpBeginner - 4 years ago 140
C# Question

Object 'respStream' can be disposed more than once in method

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?

Answer Source

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();
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download