使用的MemoryStream写入到XML [英] Using MemoryStream to write out to XML

查看:634
本文介绍了使用的MemoryStream写入到XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到两种不同的方法将数据写入到一个XML文件(处理为简洁起见省略错误)。

I have noticed two different approaches to writing out data to an XML file (error handling omitted for brevity).

已经在构建XML文档的第一种方法和只要简单的把XML保存到一个文件:使用

The first method has you build the XML document and then simply save the XML to a file:

using (XmlWriter writer = XmlWriter.Create(fileName))
{
    writer.WriteStartDocument(true);
    writer.WriteStartElement("parentelement");
    writer.WriteEndElement();
    writer.WriteEndDocument();
}

已创建一个MemoryStream,然后将MemoryStream保存到第二个方法文件:

The second method has you create a MemoryStream, and then save the MemoryStream to a file:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms, settings))
{
    writer.WriteStartDocument(true);
    writer.WriteStartElement("parentelement");
    writer.WriteEndElement();
    writer.WriteEndDocument();
}

using (FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write))
{
    ms.WriteTo(fs);
    ms.Dispose();
}



我猜逻辑用于使用一个MemoryStream是确保XML文件可以尝试保存文件之​​前建成。请问将MemoryStream方法提供一个原子写事件和/或写入防止问题,同时要添加条目到XML文件?

I'm guessing the logic for using a MemoryStream is to ensure the XML file can be built before trying to save the file. Would the the MemoryStream method provide for an Atomic write event and/or protect against write issues while you are adding entries into the XML file?

谁能解释这实际上是必要或只是一个矫枉过正的方式来不必要的代码行添加到我的项目?

Can anyone explain if this is actually necessary or just an overkill way to add unnecessary lines of code to my project?

推荐答案

MemoryStream的的版本是在这个场合浪费。 的MemoryStream 如果您要执行样的工作,但不想一个实际的文件是非常有用的。如果你的写入文件,然后只写入文件。这避免了需要缓冲存储器中的所有数据。

The MemoryStream version is wasteful on this occasion. MemoryStream is useful if you want to perform Stream-like work, but don't want an actual file. If you are writing a file, then just write to the file. This avoids the need to buffer all the data in memory.

这篇关于使用的MemoryStream写入到XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆