Clear contents of a file in C#
This post will discuss how to clear the contents of a file in C#.
1. Using File.WriteAllText() method
The File.WriteAllText() method is commonly used to write some text to a file. To clear the contents of a file, you can simply write empty text to a file using the WriteAllText() method, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\data.txt"; File.WriteAllText(path, string.Empty); } } |
Note that the File.WriteAllText() method will create a new file if the file is not located in the specified path.
2. Using FileStream.SetLength() method
Another option is to create a new filestream, set the length of filestream to 0 using the FileStream.SetLength() method, and finally flush the stream. Here’s a sample of its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\data.txt"; using (FileStream fs = new FileStream(path, FileMode.Open)) { fs.SetLength(0); } } } |
Instead of opening the stream in FileMode.Open mode, you can directly open the stream with the FileMode.Truncate mode, and close it. This will clear the content of the file without even having to call the FileStream.SetLength() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\data.txt"; using (FileStream fs = new FileStream(path, FileMode.Truncate)) { } } } |
Note that both the above solutions will throw FileNotFoundException if the system could not find the specified file.
3. Using File.Create() method
Finally, you can use the File.Create() method, which creates a file at the specified path if it does not exist. If the file does exist, and it is not read-only, the contents are overwritten.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\data.txt"; File.Create(path).Close(); } } |
That’s all about clearing the contents of 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 :)