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.
Open the document in Microsoft Word or another word processor. Move the mouse cursor to the beginning of the word you want to delete. Press and hold the left mouse button, then drag the mouse to the right until the entire word is highlighted. Press Backspace or Delete to delete the word.
Clear a Text File Using the open() Function in write Mode Opening a file in write mode clears its data. Also, if the file specified doesn't exist, Python will create a new one. The simplest way to delete a file is to use open() and assign it to a new variable in write mode.
String myPath = @"C:\New\amit. txt"; Now, use the File. Delete method to delete the file.
remove() method in Python can be used to remove files, and the os. rmdir() method can be used to delete an empty folder. The shutil. rmtree() method can be used to delete a folder along with all of its files.
You can look at the Truncate method
FileInfo fi = new FileInfo(@"Default\DefaultProfile.txt");
using(TextWriter txtWriter = new StreamWriter(fi.Open(FileMode.Truncate)))
{
txtWriter.Write("Write your line or content here");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With