.NET Framework Strip unwanted lines from a text file


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.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.ReadLines(inputPath).Where(x => !String.IsNullOrWhiteSpace(x)));