Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# File.ReadAllLines doesn't read blank lines

I am using c# for reading some txt documents and writing/deleting some lines in them
I have to read a text document, delete some of it’s lines and then save it again in the same path.
It worked all good until I realized that it doesn’t read empty lines or when there is just a space in a new line :(.

Here’s my text file structure:

-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted
****here comes the empty line****

Here’s my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        List<string> myLines = File.ReadAllLines(path).ToList();
        
        if (myLines.Count > 5)
        {
            for(int i = 7; i >= 5; i--)
            {
                myLines.RemoveAt(i);
            }
            File.WriteAllLines(path, myLines.ToArray());
        }

So I don’t know why when I run File.ReadAllLines will give me 7 lines (ignoring the blank one) and of course after I delete something in the file, the blank line is still there.

Note: I am working with more than 100k files, either way I would just delete that specific line by hand.

Can you help me sort this out and delete that blank line? Thank you.

>Solution :

Here’s some code:

    var f = @"-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted

-Name2";

    File.WriteAllText(@"C:\temp\a.txt", f);

    var f2 = File.ReadAllLines(@"C:\temp\a.txt").ToList();

    f2.RemoveAt(7);
    f2.RemoveAt(6);
    f2.RemoveAt(5);

    File.WriteAllLines(@"C:\temp\b.txt", f2);

Open the two resulting files a.txt and b.txt in c:\temp (make sure you have a c:\temp) – the a has blank lines, the b has no interim blank lines or address2/3

enter image description here

..but do note that b has a blank line at the end, because File.WriteAllLines will end the final line (Name2 in my example) with a CRLF.

If this is what you’re talking about/you don’t want, consider something else instead, perhaps:

File.WriteAllText(@"C:\temp\b.txt", string.Join(Environment.NewLine, f2));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading