C# 如何在使用TextWriter时截断流
这段代码应该是不言自明的:C# 如何在使用TextWriter时截断流,c#,.net,stream,C#,.net,Stream,这段代码应该是不言自明的: 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); } 我想使用Text
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);
}
}
如果要刷新流,则需要执行此操作
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构造函数的使用。注意最后一个参数:您可以告诉它让流保持打开状态。使用StreamWriter构造函数。注意最后一个参数:您可以告诉它保持流打开。您确定
Save
关闭流吗?正在使用关闭文本编写器
。也许这会奏效:
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
,这也会导致底层流的刷新。仅刷新文件流
可能不包括仍在TextWriter
中缓冲的数据是否确实保存
关闭流?正在使用关闭文本编写器
。也许这会奏效:
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
,这也会导致底层流的刷新。仅刷新文件流
可能不包括仍在TextWriter
中缓冲的数据我认为您可能需要在xd.Save()之后调用xd.Flush()否则,它可能不会将其缓冲区刷新到fs。好的,我将在复制他的时更新我的错误code@MatthewWatson:我想你的意思是tw.Flush()
。谢谢。我已经想好了,我需要将SetLength移到外部的“using”中。我想我一定是有心理障碍,没有意识到它也必须在内部:-)那tw.Flush()
应该在xd.Save(tw)
之后。我想你可能需要在xd.Save()之后调用xd.Flush()否则,它可能不会将其缓冲区刷新到fs。好的,我将在复制他的时更新我的错误code@MatthewWatson:我想你的意思是tw.Flush()
。谢谢。我已经想好了,我需要将SetLength移到外部的“using”中。我想我一定有一个心理障碍,没有意识到它也必须在内部:-)那tw.Flush()
应该在xd.Save(tw)
之后。Andy请记住,当在using
子句周围包装代码时,一旦进程离开using(){/code>块,对象被自动释放,底层对象被关闭。我只是好奇,你能展示一下你如何/在哪里使用XDocument xd=…
?Andy请记住,当你在using
子句中包装代码时,一旦你的进程离开using(){}
块,对象被自动处理,底层对象被关闭。我只是好奇,你能展示一下你是如何/在哪里使用XDocument xd=…
?谢谢你-这不是我一直在寻找的答案,但我不知道过载,这肯定是我在未来的银行中会用到的-这不是我想要的答案我一直在寻找,但我不知道超负荷,这肯定是我将来会使用的东西