的FileStream和StreamWriter - 如何写后截断文件的剩余部分?剩余、如何写、部分、文件

2023-09-03 00:47:18 作者:宠我一世

 变种FS =新的FileStream(文件路径,FileMode.OpenOrCreate,FileAccess.ReadWrite);
使用(VAR作家=新的StreamWriter(FS))
    writer.Write(....);
 

如果文件previously包含的文本和新写的文字比已经在文件中短,我该如何确保该文件中的废弃尾随内容将被截断?

请注意,在截断模式打开该文件不是在这种情况下的一个选项。当我收到的FileStream 对象的文件已经打开。上述code是只是为了说明流的属性。

怎么写呀

修改

展开下面的答案,解决的办法是:

 变种FS =新的FileStream(文件路径,FileMode.OpenOrCreate,FileAccess.ReadWrite);
使用(VAR作家=新的StreamWriter(FS))
{
    writer.Write(....);
    fs.SetLength(fs.Position);
}
 

解决方案

使用SetLength设置文件的新长度 - 该文件应被截断

请参阅this回答以一个相关的问题。

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?

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.

EDIT

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(....);
    fs.SetLength(fs.Position);
}

解决方案

Use SetLength to set the new length of the file - the file should get truncated.

See this answer to a related question.