4
votes

I'm just looking for some advice from someone more experienced than me really (wont be hard).

The following code...

        XmlSerializer serializer = new XmlSerializer(typeof(Installation));
        using (var sw = new StringWriter()) {
            using (var xw = XmlWriter.Create(sw)) {
                serializer.Serialize(xw, Installation);
            }
            xmlResult = sw.ToString();
        }

has the following report in the code analysis...

CA2202 Do not dispose objects multiple times Object 'sw' can be disposed more than once in method 'Views_Commissioning_installationSubsidyForm.SaveInstall(string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 766 nc1_DealerPortal installationSubsidyForm.aspx.cs 766

Can anyone explain how I'm disposing of 'sw' more than once? What am I doing wrong here?

1

1 Answers

1
votes

StringWriter will be disposed by the XmlWriter, so by having 2 using statements it will get disposed twice change you code as below:

XmlSerializer serializer = new XmlSerializer(typeof(Installation));
var sw = new StringWriter()) 
using (var xw = XmlWriter.Create(sw)) 
{
    serializer.Serialize(xw, Installation);
    xmlResult = sw.ToString();
}