Remove blank lines in a text file

Viewed 45837

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

4 Answers

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

Related