This post will discuss how to truncate a file in C#.

The standard solution to truncate a file in C# is using the FileStream.SetLength() method. It sets the length of the current file stream to the specified value. The stream will be truncated if the value is less than the stream’s current length.

The idea is to create a new file stream and use the SetLength() method to set the length of the file stream to the desired length. This approach is demonstrated below:

Download Code

 
In order for SetLength() to work, the stream should support both writing and seeking operations. The above solution uses the FileMode.Open mode, which will throw a FileNotFoundException exception if the file does not exist. Consider using the FileMode.OpenOrCreate mode that creates a new file if it doesn’t exist.

 
Note that the stream must be flushed to reflect changes in the physical file. If you need to clear the contents of a file, you can pass the value 0 to the SetLength() method.

Download Code

 
Alternatively, you can open the file stream in FileMode.Truncate mode, and then close it without invoking the SetLength() method. This will truncate the file down to 0 bytes.

Download Code

That’s all about truncating a file in C#.