.NET File.WriteAllLines leaves empty line at the end of file

The WriteAllLines method will write out each line in your array followed by a line break. This means that you will always get this "empty line" in your file.

The point made in the post you linked is that when running ReadAllLines that considers a line to be characters terminated by a line break. So when you use the read method on the file you've just written you should get the exact same lines back.

If you are reading the file in a different way then you will have to deal with linebreaks yourself.

Essentially what you are seeing is Expected Behaviour.


As others have pointed out, that's just how it works. Here is a method that does it without the extra newline:

public static class FileExt
{
    public static void WriteAllLinesBetter(string path, params string[] lines)
    {
        if (path == null)
            throw new ArgumentNullException("path");
        if (lines == null)
            throw new ArgumentNullException("lines");

        using (var stream = File.OpenWrite(path))
        using (StreamWriter writer = new StreamWriter(stream))
        {
            if (lines.Length > 0)
            {
                for (int i = 0; i < lines.Length - 1; i++)
                {
                    writer.WriteLine(lines[i]);
                }
                writer.Write(lines[lines.Length - 1]);
            }
        }
    }
}

Usage:

FileExt.WriteAllLinesBetter("test.txt", "a", "b", "c");

Writes:

aenter
benter
c

You can also save a file with WriteAllText and join array of lines manually like:

File.WriteAllText(file, String.Join("\r\n",correctedLines));

Tags:

.Net

Arrays

Line