75

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

2
  • 3
    If the file doesn't exist, do you want a FileNotFoundException?
    – SLaks
    Apr 23, 2010 at 0:38
  • var fileStream = File.Open("path", FileMode.Open); fileStream.SetLength(0); Apr 27, 2021 at 13:09

7 Answers 7

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

Alternatively,

File.Create(path).Close();
3
  • 4
    Wow, even shorter than mine! +1 Apr 23, 2010 at 0:35
  • 1
    what do you mean "shorter" than yours?
    – Zer0
    Oct 13, 2015 at 18:31
  • @F4z: Far fewer characters.
    – SLaks
    Oct 13, 2015 at 18:57
20

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

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

 }

Will create or overwrite a file.

2
  • 2
    Since there's no code in the block, the using statement offers no advantage over .Close().
    – SLaks
    Apr 23, 2010 at 0:36
  • 8
    I'm assuming he'd be doing something with the file.
    – womp
    Apr 23, 2010 at 16:01
4

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

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

Another short version:

System.IO.File.WriteAllBytes(path, new byte[0]);
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();
}
-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);
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.