[英]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.