Remove blank lines in a text file

Mike picture Mike · Jun 25, 2011 · Viewed 40.8k times · Source

How can you remove blank lines from a text file in C#?

Answer

Alex Aza picture Alex Aza · Jun 25, 2011

If file is small:

var lines = File.ReadAllLines(fileName).Where(arg => !string.IsNullOrWhiteSpace(arg));
File.WriteAllLines(fileName, lines);

If file is huge:

var tempFileName = Path.GetTempFileName();
try
{
    using (var streamReader = new StreamReader(inptuFileName))
    using (var streamWriter = new StreamWriter(tempFileName))
    {
        string line;
        while ((line = streamReader.ReadLine()) != null)
        {
            if (!string.IsNullOrWhiteSpace(line))
                streamWriter.WriteLine(line);
        }
    }
    File.Copy(tempFileName, inptuFileName, true);
}
finally
{
    File.Delete(tempFileName);
}