How to truncate a file in C#?

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

Here is the syntax −

public override void SetLength (long value);

Here, int64 = Length of the stream

Value < current Length

If the value is less than the current length of the stream: The stream is truncated. If the current position is greater than the new length, the current position is moved to the last byte of the stream.

Value > current Length

The stream is expanded, and the current position remains the same. If the stream is expanded, the contents of the stream between the old and the new length are undefined.

The following is an example showing the code snippet −

public void Export(string path) {
   FileStream oStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);

Updated on: 22-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started