Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all previous text before writing

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.

like image 406
Abdur Rahim Avatar asked Dec 28 '12 15:12

Abdur Rahim


People also ask

How do you remove text from a document?

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.

How do you clear a text file and write it in Python?

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.

How do you clear a text file in C#?

String myPath = @"C:\New\amit. txt"; Now, use the File. Delete method to delete the file.

How do you clear a Python 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.


2 Answers

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");
}
like image 64
MethodMan Avatar answered Mar 29 '23 19:03

MethodMan


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.

like image 36
Cᴏʀʏ Avatar answered Mar 29 '23 18:03

Cᴏʀʏ