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.
System.IO.File.Delete
, or one of theSystem.IO.FileStream
constructor overloads specifyingFileMode.Create
Simply change the second parameter from
true
tofalse
in the contructor ofStreamWriter
.See StreamWriter Contructor
The most straightforward and efficient technique is to use the StreamWriter constructor's boolean parameter. When it's set to false it overwrites the file with the current operation. For instance, I had to save output of a mathematical operation to a text file. Each time I wanted ONLY the current answer in the text file. So, on the first StreamWriter operation, I set the boolean value to false and the subsequent calls had the bool val set to true. The result is that for each new operation, the previous answer is overwritten and only the new answer is displayed.
You can use
FileMode.Truncate
. Code will look likeYou can look at the Truncate method
You could just write an empty string to the existing file:
Or change the second parameter in the
StreamWriter
constructor tofalse
to replace the file contents instead of appending to the file.