Strip unwanted lines from a text file

suggest change

To change a text file is not easy because its content must be moved around. For small files easiest method is to read its content in memory and then write back modified text.

In this example we read all lines from a file and drop all blank lines then we write back to original path:

File.WriteAllLines(path,
    File.ReadAllLines(path).Where(x => !String.IsNullOrWhiteSpace(x)));

If file is too big to load it in memory and output path is different from input path:

File.WriteAllLines(outputPath,
    File.ReadLines(inputPath).Where(x => !String.IsNullOrWhiteSpace(x)));

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents