Truncate a file in C#
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.IO; public class Program { public static void Main() { string path = @"C:\data.txt"; int sizeInBytes = 2048; using (FileStream fs = new FileStream(path, FileMode.Open)) { fs.SetLength(sizeInBytes); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.IO; public class Program { public static void Main() { string path = @"C:\data.txt"; using (FileStream fs = new FileStream(path, FileMode.Open)) { fs.SetLength(0); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; using System.IO; public class Program { public static void Main() { string path = @"C:\data.txt"; using (FileStream fs = new FileStream(path, FileMode.Truncate)) { } } } |
That’s all about truncating a file in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)