0

I have some code like this.

using (StreamWriter sw = new StreamWriter(@"c:\SomeFile.txt"))
{
    using (IDataReader reader = SomeMethodThatReturnsADataReader())
    {
        while (reader.Read())
        {
            // using sw and reader here
        }
    }

    sw.Close();
}

Code Analysis reporting following warning.

CA2202 Do not dispose objects multiple times Object 'sw' can be disposed more than once in method . To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

What am I doing wrong here?

crazy novice
  • 1,757
  • 3
  • 14
  • 36

1 Answers1

1

As we see from StreamWriter.Dispose(), the Close method is called inside it.

protected override void Dispose(bool disposing)
{
    try
    {
        if (this.stream != null && (disposing || (this.LeaveOpen && this.stream is __ConsoleStream)))
        {
            this.CheckAsyncTaskInProgress();
            this.Flush(true, true);
            if (this.mdaHelper != null)
            {
                GC.SuppressFinalize(this.mdaHelper);
            }
        }
    }
    finally
    {
        if (!this.LeaveOpen && this.stream != null)
        {
            try
            {
                if (disposing)
                {
                    this.stream.Close();
                }
            }
            finally
            {
                this.stream = null;
                this.byteBuffer = null;
                this.charBuffer = null;
                this.encoding = null;
                this.encoder = null;
                this.charLen = 0;
                base.Dispose(disposing);
            }
        }
    }
}
Mansfield
  • 14,445
  • 18
  • 76
  • 112