Morano88
Morano88

Reputation: 2077

Clearing content of text file using C#

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

Upvotes: 78

Views: 162105

Answers (7)

Nik
Nik

Reputation: 51

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

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

Upvotes: 5

Creek Drop
Creek Drop

Reputation: 594

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();
}

Upvotes: 0

Harry007
Harry007

Reputation: 59

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);
}

Upvotes: -2

Ivan Kochurkin
Ivan Kochurkin

Reputation: 4481

Another short version:

System.IO.File.WriteAllBytes(path, new byte[0]);

Upvotes: 2

womp
womp

Reputation: 116977

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

 }

Will create or overwrite a file.

Upvotes: 5

Dean Harding
Dean Harding

Reputation: 72658

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

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

Upvotes: 21

SLaks
SLaks

Reputation: 887479

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

Upvotes: 191

Related Questions