Mike
Mike

Reputation: 249

Remove blank lines in a text file

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

Upvotes: 16

Views: 51609

Answers (4)

Dilip Kumar Choudhary
Dilip Kumar Choudhary

Reputation: 469

We can achieve it very easily by using LINQ technique for Huge or small file. 1.Explanation: It will read the file and skip all empty lines and store all the data into an string array

                    string[] text = File.ReadAllLines(path with file name).Where(s => s.Trim() != string.Empty).ToArray();
  1. It will delete that file.

                    File.Delete(path with file name);
    
  2. It will create new file as same name and append all the array data into new file

                    File.WriteAllLines(path with file name, text);
    

Complete Code

                string[] text = File.ReadAllLines(LoraWan_Parameter_Check_Tool.Properties.Settings.Default.csv_file_path.ToString()).Where(s => s.Trim() != string.Empty).ToArray();
                File.Delete(LoraWan_Parameter_Check_Tool.Properties.Settings.Default.csv_file_path.ToString());
                File.WriteAllLines(LoraWan_Parameter_Check_Tool.Properties.Settings.Default.csv_file_path.ToString(), text);
  1. Problem solved

Thank you

Upvotes: 1

Daniel Iankov
Daniel Iankov

Reputation: 306

Read all of the contents of a file into a string then just run

string output = null;
try {
    output = Regex.Replace(input, @"^\s*$", "", RegexOptions.Multiline);
} catch (Exception e) {

}

Other similar options can be found in How to remove empty lines from a formatted string?

Upvotes: 4

Alex Aza
Alex Aza

Reputation: 78457

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);
}

Upvotes: 38

Mårten Wikström
Mårten Wikström

Reputation: 11344

File.WriteAllLines(path, File.ReadAllLines(path).Where(l => !string.IsNullOrWhiteSpace(l)));

Upvotes: 11

Related Questions