繁体   English   中英

使用TextWriter时如何截断流

[英]How to truncate a stream when using a TextWriter

该代码段应该是不言自明的:

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);
}

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

在现实世界中,我实际上并没有序列化到文件,而是在我的控制范围之外进行了其他类型的流传输,因此要先删除该文件并不容易。

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

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);
  }
}

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

您确定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();
  }
}

请注意,我刷新了TextWriter ,这也会导致底层流的刷新。 仅刷新FileStream可能不包括仍在TextWriter缓冲的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM