75

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

Morano88
  • 2,047
  • 4
  • 25
  • 44

7 Answers7

185
File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
20

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

using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}
Dean Harding
  • 71,468
  • 13
  • 145
  • 180
5
 using (FileStream fs = File.Create(path))
 {

 }

Will create or overwrite a file.

womp
  • 115,835
  • 26
  • 236
  • 269
4

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

File.WriteAllText(@"FilePath", "");
Nik
  • 41
  • 1
2

Another short version:

System.IO.File.WriteAllBytes(path, new byte[0]);
Ivan Kochurkin
  • 4,413
  • 8
  • 45
  • 80
0

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();
}
Creek Drop
  • 464
  • 3
  • 13
-3

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);
}
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
Harry007
  • 47
  • 1
  • 7