Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileStream and StreamWriter - How to truncate the remainder of the file after writing?

Tags:

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(....);
    writer.Flush();
    fs.SetLength(fs.Position);
}
like image 399
Nathan Ridley Avatar asked Dec 11 '11 13:12

Nathan Ridley


People also ask

How do you truncate a file in C#?

How to truncate a file in C#? To truncate a file in C#, use the FileStream. SetLength method.

What is the difference between StreamWriter and TextWriter?

The StreamWriter class in C# is used for writing characters to a stream. It uses the TextWriter class as a base class and provides the overload methods for writing data into a file. The StreamWriter is mainly used for writing multiple characters of data into a file.


2 Answers

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

See this answer to a related question.

like image 158
Oded Avatar answered Sep 21 '22 15:09

Oded


you could try writer.BaseStream.SetLength(writer.BaseStream.Position) although I'm not sure how well that would work.

For a FileStream I think that should truncate the file to the current position.

like image 37
Russell Troywest Avatar answered Sep 24 '22 15:09

Russell Troywest