的FileStream和StreamWriter - 如何写后截断文件的剩余部分? [英] FileStream and StreamWriter - How to truncate the remainder of the file after writing?

查看:467
本文介绍了的FileStream和StreamWriter - 如何写后截断文件的剩余部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 变种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);
}
 

解决方案

使用<一个href="http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx"><$c$c>SetLength设置文件的新长度 - 该文件应被截断

请参阅<一href="http://stackoverflow.com/questions/8288401/c-sharp-filestream-both-lock-a-file-and-at-the-same-time-be-able-to-read-it-w/8288413#8288413">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.

这篇关于的FileStream和StreamWriter - 如何写后截断文件的剩余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆