Strip unwanted lines from a text file
suggest changeChanging 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)));
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents