How to truncate a file in C#?

CsharpProgrammingServer Side Programming

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);
   oStream.SetLength(Length);
}
raja
Published on 31-Aug-2018 09:40:22

Advertisements