[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Remove blank lines from .txt file

Posted on 2007-10-08
8
Medium Priority
?
3,985 Views
Last Modified: 2008-01-09
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.
0
Comment
Question by:Antonio King
  • 4
  • 4
8 Comments
 
LVL 11

Expert Comment

by:udhayakumard
ID: 20034980
            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
 
LVL 11

Expert Comment

by:udhayakumard
ID: 20035006
Simple:

            string data = File.ReadAllText("test.txt").Replace("\r\n\r\n", "\r\n");            
            File.Delete("test.txt");
            File.WriteAllText("test.txt", data);
0
 
LVL 11

Accepted Solution

by:
udhayakumard earned 1200 total points
ID: 20035013
More simple:

string data = File.ReadAllText("test.txt").Replace("\r\n\r\n", "\r\n");
File.WriteAllText("test.txt", data);
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 20036847
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
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 20036867
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
 
LVL 30

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 800 total points
ID: 20037922
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
 
LVL 11

Expert Comment

by:udhayakumard
ID: 20038721
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
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 20044236
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

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Loops Section Overview
Suggested Courses
Course of the Month18 days, 18 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question