Clearing content of text file using C#

C#.NetTextFile

C# Problem Overview


How can I clear the content of a text file using C# ?

C# Solutions


Solution 1 - C#

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

Solution 2 - C#

Just open the file with the FileMode.Truncate flag, then close it:

using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}

Solution 3 - C#

 using (FileStream fs = File.Create(path))
 {
           
 }

Will create or overwrite a file.

Solution 4 - C#

You can clear contents of a file just like writing contents in the file but replacing the texts with ""

File.WriteAllText(@"FilePath", "");

Solution 5 - C#

Another short version:

System.IO.File.WriteAllBytes(path, new byte[0]);

Solution 6 - C#

Simply write to file string.Empty, when append is set to false in StreamWriter. I think this one is easiest to understand for beginner.

private void ClearFile()
{
    if (!File.Exists("TextFile.txt"))
        File.Create("TextFile.txt");

    TextWriter tw = new StreamWriter("TextFile.txt", false);
    tw.Write(string.Empty);
    tw.Close();
}

Solution 7 - C#

You can use always stream writer.It will erase old data and append new one each time.

using (StreamWriter sw = new StreamWriter(filePath))
{                            
    getNumberOfControls(frm1,sw);
}

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
QuestionMorano88View Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#Dean HardingView Answer on Stackoverflow
Solution 3 - C#wompView Answer on Stackoverflow
Solution 4 - C#NikView Answer on Stackoverflow
Solution 5 - C#Ivan KochurkinView Answer on Stackoverflow
Solution 6 - C#Creek DropView Answer on Stackoverflow
Solution 7 - C#Harry007View Answer on Stackoverflow