How can I clear the content of a text file using C# ?
7 Answers
File.WriteAllText(path, String.Empty);
Alternatively,
File.Create(path).Close();
-
4
-
1
-
Just open the file with the FileMode.Truncate flag, then close it:
using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}
using (FileStream fs = File.Create(path))
{
}
Will create or overwrite a file.
-
2Since there's no code in the block, the
using
statement offers no advantage over.Close()
.– SLaksApr 23, 2010 at 0:36 -
8
You can clear contents of a file just like writing contents in the file but replacing the texts with ""
File.WriteAllText(@"FilePath", "");
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();
}
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);
}
FileNotFoundException
?