Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove blank lines in a text file

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

like image 605
Mike Avatar asked Jun 25 '11 19:06

Mike


2 Answers

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);
}
like image 148
Alex Aza Avatar answered Oct 13 '22 00:10

Alex Aza


File.WriteAllLines(path, File.ReadAllLines(path).Where(l => !string.IsNullOrWhiteSpace(l)));
like image 32
Mårten Wikström Avatar answered Oct 13 '22 01:10

Mårten Wikström