如何正确打开 FileStream 以与 XDocument 一起使用 [英] How to correctly open a FileStream for usage with an XDocument

查看:33
本文介绍了如何正确打开 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();
}

非常感谢任何帮助.

推荐答案

加载文档,关闭流,再次保存.这也意味着您可以以更简单的方式打开它:)

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天全站免登陆