Arnthor
Arnthor

Reputation: 2623

C# - trim text file contents to specified line number

I have a very annoying bug, code generation tool has generated like 20,000 lines of rubbish in file. Removing it all by hand, is, well, rather hard, so I want to write a program that does so. Good news is that source code file contains needful info on lines 1 - 300, and then rubbish all the way down to line 20,000.

I'm not very experienced in handling files in C#, and couldn't google up method I need. Are there any ways to do so?

Upvotes: 0

Views: 1011

Answers (2)

Ankur
Ankur

Reputation: 33657

Below is an example code to do this file trimming:

public static void TrimFile(string fileName,int start, int end)
        {
            File.WriteAllLines(fileName,
                File.ReadAllLines(fileName)
                    .Skip(start - 1).Take(end - start));

        }

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039170

File.WriteAllLines("test.txt", File.ReadAllLines("test.txt").Take(300));

Upvotes: 4

Related Questions