2

这个片段应该是不言自明的:

XDocument xd = ....
using (FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite))
{
  using (TextWriter tw = new StreamWriter(fs))
  {
    xd.Save(tw);
  }
  fs.Flush();
  fs.SetLength(fs.Position);
}

我想XDocument使用 a 将我的流序列化为流TextWriter,然后在流结束后截断流。不幸的是,该Save()操作似乎关闭了流,所以我的Flush()调用生成了一个异常。

在现实世界中,我实际上并没有序列化到文件,而是我无法控制的其他类型的流,所以这不仅仅是先删除文件那么简单。

4

3 回答 3

2

如果要刷新流,则需要执行此操作

using (FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite))
{
  using (TextWriter tw = new StreamWriter(fs))
  {
    tw.Flush();
    xd.Save(tw);
    fs.SetLength(fs.Position);
  }
}
于 2013-01-31T15:40:13.643 回答
2

使用StreamWriter 构造函数的这个重载。注意最后一个参数:您可以告诉它让流保持打开状态。

于 2013-01-31T15:41:58.940 回答
0

你确定Save关闭流吗?TextWriter正在结束时using关闭。也许这会起作用:

using (FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite))
{
  var TextWriter tw = new StreamWriter(fs);
  try
  {
    xd.Save(tw);
    tw.Flush();
    fs.SetLength(fs.Position);
  }
  finally
  {
    tw.Dispose();
  }
}

Note that I flush the TextWriter, which also causes a flush of the underlying stream. Just flushing the FileStream might not include the data that's still buffered in the TextWriter.

于 2013-01-31T15:45:39.900 回答