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#)
Step 1 − Read file path and line number to remove at runtime. Step 2 − Open file in read mode and store in source file. Step 3 − Create and open a temporary file in write mode and store its reference in Temporary file. Step 4 − Initialize a count = 1 to track line number.
Deleting a Line Press the Esc key to go to normal mode. Place the cursor on the line you want to delete. Type dd and hit Enter to remove the line.
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); } } }
The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.
There is no generic delete-a-line-from-file function, as far as I know.
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