0

How can I delete text from text file? For example I have some text and every time I would change the text box text in a file will change. This is what I mean:


StreamWriter = sw;
StreamReader = sr;
string path = "file.txt";
string text = txtText.Text;
if(!File.Exists(path))
{
sw = File.CreateText(path)
}
else
{
sw = new StreamWriter(path, true)
}
//here I want to delete previous line
sw.WriteLine(text)
sw.Close()
  • I imagine in general the process would involve reading all the file's contents into memory, modifying the data as you see fit, and then overwriting the entire file with the new data. Serializing data to standard file formats can make this easy, but if the file is your own custom format then you'll write your own custom logic. Either way, when you try to read from / write to the file, where do you get stuck? – David Nov 07 '21 at 15:11
  • Does this answer your question? [How to delete a line from a text file in C#?](https://stackoverflow.com/questions/668907/how-to-delete-a-line-from-a-text-file-in-c) – Quince Ngomane Nov 08 '21 at 13:42

1 Answers1

0

you have to replace

sw = new StreamWriter(path, true)

with

sw = new StreamWriter(path, false)

since boolean parameter defines append new text or not

and I recommend to use using to dispose the resource after using

if (!File.Exists(path))
    {
        sw = File.CreateText(path);
    }
    else
    {
        sw = new StreamWriter(path, false);
    }
    
    using (sw)
    {
            sw.WriteLine(text);
    };
Serge
  • 40,935
  • 4
  • 18
  • 45