2

all

This question is related to two methods in System.IO.File:

File.WriteAllLines and File.ReadAllLines

When I save a List[string] ListA by using

File.WriteAllLines("filename",ListA.ToArray());

There will be an empty line append to the output file.

So each time I load this file by calling File.ReadAllLines, I will always get one more empty line.

It's annoying, as I have to "remove" it manually each time.

Does anyone suffering same problem? And how you deal with it?

Thanks

Steven Du
  • 1,681
  • 19
  • 35

1 Answers1

2

Nope, I can't reproduce that:

using System;
using System.Collections.Generic;
using System.IO;

class Test
{
    static void Main()
    {
        string[] lines = { "first", "second", "third" };

        for (int i = 0; i < 10; i++)
        {
            File.WriteAllLines("test.txt", lines);

            lines = File.ReadAllLines("test.txt");
            Console.WriteLine("Number of lines read: {0}", lines.Length);
        }
    }
}

It sounds like it's probably something to do with what you're doing with the lines... which you haven't told us.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I use List of string and save as File.WriteAllLines("filename",ListA.toArry()); – Steven Du Jan 17 '12 at 11:25
  • @DuSijun: Well there's no such method as `toArry` to I suspect this isn't the standard `List`... or you're giving us the wrong code. You need to provide more context, but basically I don't think you should be blaming `File.WriteAllLines` or `File.ReadAllLines`. – Jon Skeet Jan 17 '12 at 11:26
  • Sorry for that is ListA.ToArray(); – Steven Du Jan 17 '12 at 11:35
  • @DuSijun: Well then the problem is still somewhere else - just creating a list from an array and then converting the list back to an array isn't going to add entries. Please try to show the problem in a short but complete program - like mine, but showing the error. – Jon Skeet Jan 17 '12 at 11:36
  • Thanks, for your reply, I think there are something wrong with my data,that's my problem but not the WritAllLines. – Steven Du Jan 17 '12 at 11:57
  • 1
    http://stackoverflow.com/questions/11689337/net-file-writealllines-leaves-empty-line-at-the-end-of-file – Nigiri Sep 04 '13 at 06:30
  • @JonSkeet an answer to another question contradicts this conclusion: https://stackoverflow.com/a/11689503/3195477 – StayOnTarget Nov 07 '18 at 18:50
  • @DaveInCaz: I think it depends on what you mean by an empty line. There will be a line break at the very end of the file, yes. But the OP is calling ReadAllLines which handles that fine, without adding a spurious line. The answer you linked to doesn't contradict that as far as I can see. – Jon Skeet Nov 08 '18 at 07:12