How to dispose XmlDocument

三世轮回 提交于 2020-05-29 06:40:12

问题


I am creating a XmlDocument using a stream and do some changes in the XmlDocument and save the XmlDocument to the stream itself.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileStream);

////
////

////  
xmlDocument.Save(fileStream);
//how to dispose the created XmlDocument object.

now how can i destroy the XmlDocument object?


回答1:


First of all, you should not re-use streams like this. Do you really want to keep an external resource open for a long time? And will you seek the stream before you re-save the xml? And will you truncate the stream after save if it is shorter than it was before?

If for some justifiable reason the answers are true, make your XML manipulator class disposable instead:

public class MyXmlManipulator : IDisposable
{
    private FileStream fileStream;

    // ...

    public void ManipulateXml()
    {
        // your original codes here...
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~MyXmlManipulator()
    {
        Dispose(false);
    }

    protected virtual Dispose(bool disposing)
    {
        fileStream.Close();
        // etc...
    }
}

But basically I would say not to keep a long-living reference to a file stream and re-use it like that. Instead, use streams only locally and dispose them as soon as possible. All you might need globally here is just a file name.

public class MyXmlManipulator
{
    private string fileName;

    // ...

    public void ManipulateXml()
    {
        XmlDocument xmlDocument = new XmlDocument();
        using (var fs = new FileStream(fileName, FileMode.Open)
        {
            xmlDocument.Load(fs);
        }

        // ...

        // FileMode.Create will overwrite the file. No seek and truncate is needed.
        using (var fs = new FileStream(fileName, FileMode.Create)
        {
            xmlDocument.Save(fs);
        }
    }
}



回答2:


The XmlDocument class does not implement IDisposable, so there's no way to force it to release it's resources at will. If you need to free that memory the only way to do that would be xmlDocument = null; and garbage collection will handle the rest.




回答3:


XmlDocument can't be disposed because it does not implement IDisposable. The real question is why do you want to destroy the object ?

I you don't keep a reference to the object the garbage collector will get rid of it.

The only thnig you can do if you want the process to be faster is to do as Fildor said, set the object to null



来源:https://stackoverflow.com/questions/42226993/how-to-dispose-xmldocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!