这个片段应该是不言自明的:
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
将TextWriter
序列化为流,然后在结束后截断流。不幸的是,Save()
操作似乎关闭了流,因此我的Flush()
调用会生成异常。
在现实世界中,我实际上并没有序列化到文件中,而是在我的控制之外的其他类型的流,所以这不是一个简单的事情,只是首先删除文件。
答案 0 :(得分: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);
}
}
答案 1 :(得分:2)
使用StreamWriter构造函数的this overload。请注意最后一个参数:您可以告诉它让流保持打开状态。
答案 2 :(得分: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();
}
}
请注意,我刷新TextWriter
,这也会导致底层流的刷新。只是刷新FileStream
可能不包括仍在TextWriter
中缓存的数据。