如何正确打开FileStream的用法与一个XDocument [英] How to correctly open a FileStream for usage with an XDocument

查看:416
本文介绍了如何正确打开FileStream的用法与一个XDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要追加一些节点使用Linq2XML XML文档。问题中的文件正被其他进程和它们应该能够读取文件而予更新。所以,我想出了这个解决方案,这显然是不正确的方法(该方法doc.Save()将失败并说另一个进程正在使用的文件):

I want to append some nodes to an xml document using Linq2XML. The file in question is being used by other processes and they should be able to read the file while I update it. So I came up with this solution, which obviously isn't the correct way (The method doc.Save() fails and says that another process is using the file):

using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
  doc = XDocument.Load(new StreamReader(fs));
  doc.Root.Add(entry);
  doc.Save(filename);
  fs.Close();
}

任何帮助是极大AP preceated。

Any help is greatly appreceated.

推荐答案

将文档,关闭流,重新保存。这也意味着你可以在一个更简单的方法打开它:)

Load the document, close the stream, save it again. That also means you can open it in a simpler way :)

XDocument doc;

using (StreamReader reader = File.OpenText(filename))
{
  doc = XDocument.Load(reader);
  doc.Root.Add(entry);
}

doc.Save(filename);

这篇关于如何正确打开FileStream的用法与一个XDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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