Strip unwanted lines from a text file

suggest change

Changing a text file means rewriting its contents. For a small file, read the text into memory and write the modified text back. ReadLines, WriteAllLines, and IsNullOrWhiteSpace are in .NET Framework 4.

This example reads every line, drops blank lines, and writes the result back to the same path. ReadAllLines finishes reading before WriteAllLines truncates the file:

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

If the file is too large to load at once, and the output path is different from the input path, stream the lines. Do not use the same path here: ReadLines is still reading when WriteAllLines opens the file.

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