Clearing content of text file using C#

136,276

Solution 1

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

Solution 2

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

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

 }

Will create or overwrite a file.

Solution 4

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

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

Solution 5

Another short version:

System.IO.File.WriteAllBytes(path, new byte[0]);
Share:
136,276
Morano88
Author by

Morano88

Updated on July 05, 2022

Comments

  • Morano88
    Morano88 almost 2 years

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

  • Dean Harding
    Dean Harding about 14 years
    Wow, even shorter than mine! +1
  • SLaks
    SLaks about 14 years
    Since there's no code in the block, the using statement offers no advantage over .Close().
  • nuiun
    nuiun about 14 years
    I'm assuming he'd be doing something with the file.
  • Zer0
    Zer0 over 8 years
    what do you mean "shorter" than yours?
  • SLaks
    SLaks over 8 years
    @F4z: Far fewer characters.