如何在使用文本编写器时截断流
本文关键字:文本编写器 | 更新日期: 2023-09-27 17:56:46
这个片段应该是相当不言自明的:
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
中的数据。