What causes "CA2202: do not delete objects multiple times" in this code and how can I reorganize?

I have a function below that is used to serialize an object without adding an XML declaration. I just opened a project that contains it in Visual Studio 2012, and the warning “CA2202: do not delete objects multiple times” appears in Code Analysis.

Now in other cases, I fixed this warning by deleting the [object] .Close, which is not needed, but in this case I do not see what needs to be changed, and the help for the warning , being accurate, is not entirely informative as to how it is called or how to fix it.

What exactly causes a warning to be displayed and how can I reorganize it to avoid?

''' <summary>
''' Serialize an object without adding the XML declaration, etc.
''' </summary>
''' <param name="target"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function SerializeElementToText(Of T As New)(target As T) As String
    Dim serializer As New XmlSerializer(GetType(T))
    'Need to serialize without namespaces to keep it clean and tidy
    Dim emptyNS As New XmlSerializerNamespaces({XmlQualifiedName.Empty})
    'Need to remove xml declaration as we will use this as part of a larger xml file
    Dim settings As New XmlWriterSettings()
    settings.OmitXmlDeclaration = True
    settings.NewLineHandling = NewLineHandling.Entitize
    settings.Indent = True
    settings.IndentChars = (ControlChars.Tab)
    Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream, settings)
        'Serialize the item to the stream using the namespace supplied
        serializer.Serialize(writer, target, emptyNS)
        'Read the stream and return it as a string
        Return stream.ToString
    End Using 'Warning jumps to this line
End Function

I tried this, but it does not work either:

    Using stream As New StringWriter()
        Using writer As XmlWriter = XmlWriter.Create(stream, settings)
            serializer.Serialize(writer, target, emptyNS)
            Return stream.ToString
        End Using
    End Using 'Warning jumps to this line instead
+5
2

, , XmlWriter . StringWriter , XmlWriter Using.

, .NET Framework . , Dispose() , FxCop , , , Dispose().

, . StringWriter , , Using . , CA2000. . SuppressMessageAttribute, .

+12

, 2 :

Using stream As New StringWriter()
    Using writer As XmlWriter = XmlWriter.Create(stream, settings)

    End Using
End Using
0

All Articles