tags:

views:

6347

answers:

4

Hello,

I have a problem: how can I delete a line from a text file in C#?

+4  A: 

Read the file, remove the line in memory and put the contents back to the file (overwriting). If the file is large you might want to read it line for line, and creating a temp file, later replacing the original one.

Sascha
+2  A: 

I agree with John Saunders, this isn't really C# specific. However, to answer your question: you basically need to rewrite the file. There are two ways you can do this.

  • Read the whole file into memory (e.g. with File.ReadAllLines)
  • Remove the offending line (in this case it's probably easiest to convert the string array into a List<string> then remove the line)
  • Write all the rest of the lines back (e.g. with File.WriteAllLines) - potentially convert the List<string> into a string array again using ToArray

That means you have to know that you've got enough memory though. An alternative:

  • Open both the input file and a new output file (as a TextReader/TextWriter, e.g. with File.OpenText and File.CreateText)
  • Read a line (TextReader.ReadLine) - if you don't want to delete it, write it to the output file (TextWriter.WriteLine)
  • When you've read all the lines, close both the reader and the writer (if you use using statements for both, this will happen automatically)
  • If you want to replace the input with the output, delete the input file and then move the output file into place.
Jon Skeet
+1  A: 

For large files I'd to something like this

string tempFile = Path.GetTempFileName();

using(var sr = new StreamReader("file.txt"))
{
    using(var sw = new StreamWriter(tempFile))
    {
        string line;

        while((line = sr.ReadLine()) != null)
        {
             if(line != "removeme")
                 sw.WriteLine(line);
        }
    }
}

File.Delete("file.txt");
File.Move(tempFile, "file.txt");
Markus Olsson
A: 

I'd very simply:

  • Open the file for read/write
  • Read/seek through it until the start of the line you want to delete
  • Set the write pointer to the current read pointer
  • Read through to the end of the line we're deleting and skip the newline delimiters (counting the number of characters as we go, we'll call it nline)
  • Read byte-by-byte and write each byte to the file
  • When finished truncate the file to (orig_length - nline).
Adam Hawes