How can I clear the content of a text file using C# ?
Asked
Active
Viewed 1.4e+01k times
7 Answers
178
File.WriteAllText(path, String.Empty);
Alternatively,
File.Create(path).Close();
SLaks
- 837,282
- 173
- 1,862
- 1,933
19
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
- 69,493
- 11
- 141
- 178
5
using (FileStream fs = File.Create(path))
{
}
Will create or overwrite a file.
womp
- 113,785
- 25
- 233
- 264
-
2Since there's no code in the block, the `using` statement offers no advantage over `.Close()`. – SLaks Apr 23 '10 at 00:36
-
8
3
You can clear contents of a file just like writing contents in the file but replacing the texts with ""
File.WriteAllText(@"FilePath", "");
Nik
- 31
- 1
2
Another short version:
System.IO.File.WriteAllBytes(path, new byte[0]);
Ivan Kochurkin
- 4,337
- 8
- 44
- 73
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
- 339
- 2
- 7
-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
- 20,534
- 10
- 70
- 102
Harry007
- 37
- 1
- 7