如何处理 XmlDocument [英] How to dispose XmlDocument
问题描述
我正在使用流创建 XmlDocument 并在 XmlDocument 中进行一些更改并将 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.
现在如何销毁 XmlDocument 对象?
now how can i destroy the XmlDocument object?
推荐答案
首先,你不应该像这样重复使用流.你真的想长期保持外部资源开放吗?你会在重新保存 xml 之前寻找流吗?如果流比以前短,你会在保存后截断它吗?
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?
如果出于某种正当理由,答案是正确的,请改为一次性使用您的 XML 操作符类:
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);
}
}
}
这篇关于如何处理 XmlDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!