I have the function below which is used to serialize an object without adding the XML declaration. I've just opened the project containing it an Visual Studio 2012 and the Code Analysis is coming up with the 'CA2202: Do not dispose objects multiple times' warning.
Now in other cases I've fixed this warning by removing an [object].Close that wasn't needed but in this case I can't see what needs to be altered and the help for the warning while being accurate isn't exactly informative as to how it is caused or how to fix it.
What exactly is causing the warning to display and how can I refactor to avoid it?
''' <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 doesn't 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