Clear the Contents of a File

C#.NetFile

C# Problem Overview


How does one clear the contents of a file?

C# Solutions


Solution 1 - C#

You can use the File.WriteAllText method.

System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);

Solution 2 - C#

This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.

FileStream fileStream = File.Open(<path>, FileMode.Open);

/* 
 * Set the length of filestream to 0 and flush it to the physical file.
 *
 * Flushing the stream is important because this ensures that
 * the changes to the stream trickle down to the physical file.
 * 
 */
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.

Solution 3 - C#

Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.

Solution 4 - C#

The easiest way is:

File.WriteAllText(path, string.Empty)

However, I recommend you use FileStream because the first solution can throw UnauthorizedAccessException

using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
     lock(fs)
     {
          fs.SetLength(0);
     }
}

Solution 5 - C#

Try using something like

File.Create

> Creates or overwrites a file in the > specified path.

Solution 6 - C#

The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionoliveView Question on Stackoverflow
Solution 1 - C#The Scrum MeisterView Answer on Stackoverflow
Solution 2 - C#Abhay JainView Answer on Stackoverflow
Solution 3 - C#sajoshiView Answer on Stackoverflow
Solution 4 - C#Mohammad AlbayView Answer on Stackoverflow
Solution 5 - C#Adriaan StanderView Answer on Stackoverflow
Solution 6 - C#KartikyaView Answer on Stackoverflow