c# using + XmlWriter.Create = “Cannot access a closed Stream.”

主宰稳场 提交于 2019-12-05 05:09:28

Can you give us the complete stack trace of the exception? My first guess is that the XmlWriter still tries to access the stream within the Dispose() method of the XmlWriter.

In your second and fourth code example you place the StreamReader in a using-block. This causes the invocation of the Dispose() method of the StreamReader at the end of this block. This method closes both the reader and the underlying stream. After this, the Dispose() method of the XmlWriter can't access the stream anymore.

Update: Based on the stackstrace it seems I was right. The Dispose() method invokes Close(), which in turn wants to flush an already closed stream. This looks like a bug since there should be nothing left to flush.

You already gave the solution: don't close the memorystream before the XmlWriter disposes.

(I assume you know that a using-block implicitly disposes the used object, and that disposing a StreamReader or StreamWriter implicitly disposes (and closes) the underlying stream.)

just move reading from MemoryStream block on one level with writing to it.

using (var ms = new MemoryStream())
{
     using (var writer = XmlWriter.Create(ms))
    {
        var serializer = new DataContractSerializer(typeof(T));
        serializer.WriteObject(writer, objectToSave);
        writer.Flush();
        ms.Position = 0;        
    }
    using (StreamReader rdr = new StreamReader(ms))
    {
        return rdr.ReadToEnd();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!