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:

Download Code

 
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:

Download Code

 
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.

Download Code

 
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.

Download Code

That’s all about clearing the contents of a file in C#.