Remove blank lines from .txt file

How do I remove empty lines from a txt file using c#.

I had an idea that it could read all lines and copy each line that contains text to a new txt file.
Remove the original and rename the new one to the original ones name?
But not too sure on how to do this.
Antonio KingIT ManagerAsked:
Who is Participating?
 
udhayakumardConnect With a Mentor Commented:
More simple:

string data = File.ReadAllText("test.txt").Replace("\r\n\r\n", "\r\n");
File.WriteAllText("test.txt", data);
0
 
udhayakumardCommented:
            FileStream fs = new FileStream("test.txt", FileMode.Open,FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string data = sr.ReadToEnd().Replace("\r\n\r\n", "\r\n");
            sr.Close();
            fs.Close();

            File.Delete("test.txt");

            FileStream fs1 = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);            
            StreamWriter sw = new StreamWriter(fs1);            
            sw.Write(data);
            sw.Close();
            fs1.Close();
0
 
udhayakumardCommented:
Simple:

            string data = File.ReadAllText("test.txt").Replace("\r\n\r\n", "\r\n");            
            File.Delete("test.txt");
            File.WriteAllText("test.txt", data);
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
anarki_jimbelCommented:
The above examples have one major flaw: if you have, say, three blank lines one after other the code will convert it to two lines, four - to two, five - to thre, etc. So you may need to run the procedure again - not very clever...

I use different pproach - I read file to a list and add only non-blank lines (you may also add trim() method to remove lines of spaces). Code is simple enough:

        private void button2_Click(object sender, EventArgs e)
        {
            List<string> lines  = new List<string>();

            // Read file to list
            StreamReader sr = File.OpenText("C:\\atest.txt");
            string input = null;
            while ((input = sr.ReadLine()) != null)
            {
                if (input.Length > 0)
                {
                    lines.Add(input);
                }
                Console.WriteLine(input);
            }
            sr.Close();


            // Write file
            StreamWriter sw = new StreamWriter("C:\\atest2.txt");
            foreach (string line in lines)
            {
                sw.WriteLine(line);
            }
            sw.Close();
        }
0
 
anarki_jimbelCommented:
By the way, my test file (atest.txt):

"
aaa

bbb


ccc



ddd




eee





fff






gggg

.
"

Run my code and compare to result of running previous code.
0
 
anarki_jimbelConnect With a Mentor Commented:
You may also come up with the following code (modification from udhayakumard)


        private void button3_Click(object sender, EventArgs e)
        {
            string data = File.ReadAllText("C:\\atest.txt");
           
            while(data.IndexOf("\r\n\r\n") >-1){
                 data = data.Replace("\r\n\r\n", "\r\n");
            }
            File.WriteAllText("C:\\atest2.txt", data);
        }

It works fine and looks simpler than mine.
However, keep in mind that for big files this code is quite inefficient as
string operations are quite costly.

I'd prefer mine version. It might happen it consumes a bit more memory but performance will be better.
0
 
udhayakumardCommented:
anarki_jimbel, i dint find any flaw in my code... i do know what u r trying to do... After testing only i used to post my code.... It works fine
0
 
anarki_jimbelCommented:
The goal is to remove blank lines, isn't it?

Your code (accepted one) gives the following result with my test file"
"
aaa
bbb

ccc

ddd


eee


fff



gggg
.
"

So your code removes some blank lines but not all! That's why I posted my test file content - for you to test. So my improvement (assisted solution) does it's job much better.Try to prove opposite. I tried the last version of your code only, just in case.

 I don't like my solution from the point of performance. By the way, for Alan, To make my code more efficient for big files (if you need) use StringBuffer class to build output, and returm stringbuffer object. toString().
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.