Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose XmlDocument

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?

like image 292
Amal Avatar asked Mar 10 '23 21:03

Amal


2 Answers

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.

like image 149
parameter Avatar answered Mar 21 '23 11:03

parameter


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);
        }
    }
}
like image 21
György Kőszeg Avatar answered Mar 21 '23 10:03

György Kőszeg