Question

Vagelis Dermos on Thu, 13 Dec 2012 20:51:26


Hi to all

i am trying to become better

i have a code like this

             using (FileStream fs = new FileStream("Atl.xml", FileMode.Create))
            {           
            using (XmlWriter writer = XmlWriter.Create(fs))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("ATLCOMMAND");
                    writer.WriteAttributeString("USER", "aaaa");
                    writer.WriteAttributeString("PASSWORD", "fffff");
                    writer.WriteEndElement();
                    writer.WriteStartElement("ACTDATA");
                    writer.WriteAttributeString("ACTION", "PARAMS");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
            }

code analysis says that:

Object 'fs' can be disposed more than once in method 'Form1.LoadAtlData()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 52

How i must do it in order to be ok?


Sponsored



Replies

Reed Copsey, Jr on Thu, 13 Dec 2012 20:57:02


I would allow XmlWriter to create the filestream itself, instead of making it:

using (XmlWriter writer = XmlWriter.Create("Atl.xml"))
{
                    writer.WriteStartDocument();
                    writer.WriteStartElement("ATLCOMMAND");
                    writer.WriteAttributeString("USER", "aaaa");
                    writer.WriteAttributeString("PASSWORD", "fffff");
                    writer.WriteEndElement();
                    writer.WriteStartElement("ACTDATA");
                    writer.WriteAttributeString("ACTION", "PARAMS");
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
}

This will avoid the error, but also simplify your code.

That being said, this is somewhat a "false" error.  It is perfectly safe for the FileStream to be disposed more than a single time (in fact, any class which implements IDisposable correctly technically should allow multiple calls to Dispose - IDisposable's documentation specifically says that should be fine).  If you want to ignore this warning, it should be perfectly safe to do so.