Home > OS >  Delete multiple lines from text file using c#
Delete multiple lines from text file using c#

Time:01-30

I have a text file containing 100 lines. I want to delete first 20 lines from that file I have a following code

IS anyone tell me how to do that? this code only deleting 1 line. I want to delete first 20 lines

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);
        }
    }
}

CodePudding user response:

The logic of your current code only deletes the line equal to line_to_delete To resolve you would just need to change your if statement.

if (line_number > 20)  //i would suggest not hardcoding 20
{
    writer.WriteLine(line);
}
  •  Tags:  
  • Related