How to dispose XmlDocument

11,241

Solution 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);
        }
    }
}

Solution 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.

Share:
11,241
Amal
Author by

Amal

Updated on June 04, 2022

Comments

  • Amal
    Amal about 2 years

    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?