Search code examples
c#text-files

Delete specific line from a text file?


I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.

Any suggestions or examples would be greatly appreciated?

Related Questions

Efficient way to delete a line from a text file (C#)


Solution

  • If the line you want to delete is based on the content of the line:

    string line = null;
    string line_to_delete = "the line i want to delete";
    
    using (StreamReader reader = new StreamReader("C:\\input")) {
        using (StreamWriter writer = new StreamWriter("C:\\output")) {
            while ((line = reader.ReadLine()) != null) {
                if (String.Compare(line, line_to_delete) == 0)
                    continue;
    
                writer.WriteLine(line);
            }
        }
    }
    

    Or if it is based on line number:

    string line = null;
    int line_number = 0;
    int line_to_delete = 12;
    
    using (StreamReader reader = new StreamReader("C:\\input")) {
        using (StreamWriter writer = new StreamWriter("C:\\output")) {
            while ((line = reader.ReadLine()) != null) {
                line_number++;
    
                if (line_number == line_to_delete)
                    continue;
    
                writer.WriteLine(line);
            }
        }
    }