Can't seem to see why FXCop is complaining that I am disposing the memoryStream object more than once. As near as I can tell, I'm only disposing of it in the finally block.
Full error message is:
CA2202 Do not dispose objects multiple times Object 'memoryStream' can be disposed more than once in method 'MessageTransform.GetEnvelope(Message)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 48 Api MessageTransform.cs 48
var memoryStream = new MemoryStream();
try
{
var messageBuffer = message.CreateBufferedCopy(int.MaxValue);
var xPathNavigator = messageBuffer.CreateNavigator();
var xmlWriter = XmlWriter.Create(memoryStream);
xPathNavigator.WriteSubtree(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();
memoryStream.Position = 0;
var xdoc = XDocument.Load(XmlReader.Create(memoryStream));
return xdoc;
}
catch (ApplicationException e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
memoryStream.Dispose();
}
If I wrap the same code in a using block I get the same error.
using (var memoryStream = new MemoryStream()) { var messageBuffer = message.CreateBufferedCopy(int.MaxValue); var xPathNavigator = messageBuffer.CreateNavigator(); var xmlWriter = XmlWriter.Create(memoryStream); xPathNavigator.WriteSubtree(xmlWriter); xmlWriter.Flush(); xmlWriter.Close(); memoryStream.Position = 0; var xdoc = XDocument.Load(XmlReader.Create(memoryStream)); return xdoc; }
Is this just an issue with a hyperactive FXCop or does using a using block or .Dispose() somehow not apply to a System.IO.MemoryStream?
The XmlWriter
can dispose the stream from its Close
method, which is what the rule is picking up. However, this behavior is conditional and should not be invoked in an XmlWriter
created for a stream in the way you describe.