FileStream 和 StreamWriter - 如何在写入后截断文件的其余部分? [英] FileStream and StreamWriter - How to truncate the remainder of the file after writing?
问题描述
var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
using(var writer = new StreamWriter(fs))
writer.Write(....);
如果文件先前包含文本,而新编写的文本比文件中已有的文本短,我如何确保文件中过时的尾随内容被截断?
If the file previously contained text and the newly-written text is shorter than what was already in the file, how do I make sure that the obsolete trailing content in the file is truncated?
请注意,在这种情况下,不能以截断模式打开文件.当我收到 FileStream
对象时,文件已经打开.上面的代码只是为了说明流的属性.
Note that opening the file in truncate mode isn't an option in this case. The file is already open when I receive the FileStream
object. The above code is just to illustrate the stream's properties.
编辑
扩展下面的答案,解决方案是:
Expanding on the answer below, the solution is:
var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
using(var writer = new StreamWriter(fs))
{
writer.Write(....);
writer.Flush();
fs.SetLength(fs.Position);
}
推荐答案
使用 SetLength
设置文件的新长度 - 文件应该被截断.
Use SetLength
to set the new length of the file - the file should get truncated.
见 此答案 相关问题.
这篇关于FileStream 和 StreamWriter - 如何在写入后截断文件的其余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!