Remove all previous text before writing

Abdur Rahim picture Abdur Rahim · Dec 28, 2012 · Viewed 55k times · Source

I am writing a text file and each time i write i want to clear the text file.

try
{
    string fileName = "Profile//" + comboboxSelectProfile.SelectedItem.ToString() + ".txt";
    using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), true))
    {
        sw.WriteLine(fileName);
        MessageBox.Show("Default is set!");
    }
    DefaultFileName = "Default//DefaultProfile.txt";
}
catch 
{ 
}

How do I do this? I want to remove all previous content from DefaultProfile.txt.

I actually have to know the method or way (just a name could be) to remove all content from the text file.

Answer

Cᴏʀʏ picture Cᴏʀʏ · Dec 28, 2012

You could just write an empty string to the existing file:

File.WriteAllText(@"Default\DefaultProfile.txt", string.Empty);

Or change the second parameter in the StreamWriter constructor to false to replace the file contents instead of appending to the file.