How to Remove a Line From a Text File at Specific Location in C#

Sometimes, we need to remove a specific line from a text file. For instance, when working with .csv files we often need to delete the 1st record as it is the header of csv file and is not required. This post describes how to delete a specific line from your file. The below code reads myFile.txt file and removes the 1st line from the file.

Source Code

List linesList = File.ReadAllLines("myFile.txt").ToList();

linesList.RemoveAt(0);

File.WriteAllLines("myFile.txt"), linesList.ToArray());

If you want to delete any specific line, modify Line 2 above and set the line number you want to delete and you're done.

Ebook Download
View all
Learn
View all
Think. Innovate. Grow.