I have the following code, which uses a stream to open and modify an Open XML document, and then save the new binary representation of that stream:
MemoryStream stream = null;
try
{
stream = new MemoryStream();
stream.Write(this.GetBinaryRepresentation(), 0, this.GetBinaryRepresentation().Length);
using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true))
{
OfficeDocument.ModifyDocument(document);
this.SetBinaryRepresentation(stream.ToArray());
stream = null;
}
}
finally
{
if (stream != null)
{
stream.Dispose();
}
}
I had originally used two using blocks (one for the MemoryStream and the second for the WordprocessingDocument), but received warning CA2202: "Object 'stream' can be disposed more than once in method..." Per the MSDN article, I modified the code to above (converting the outer using to a try), but I am still receiving this warning.
I'm unsure of how I can structure this method to ensure that Dispose is called exactly once on the stream. I would prefer not to simply suppress this warning since the MSDN article states that you shouldn't rely on Dispose being safely callable multiple times.
Disposing of an object multiple times should always be safe. From the documentation for Dispose:
If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times.
That being said, a using statement is definitely the way to go here. The only reason you'd receive that method was if you were explicitly disposing of the object, which would not be required, as the using statement should always dispose the object exactly once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With