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);
}
How to truncate a file in C#? To truncate a file in C#, use the FileStream. SetLength method.
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.
Use SetLength
to set the new length of the file - the file should get truncated.
See this answer to a related question.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With