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

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


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:

aenterbenterc


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.


@Virtlink solution is almost perfect. In fact there is a scenario where you will get garbage at the end of the file - when the file exist and its content is bigger than the new content. Before wrting the new file content, just reset the file lenght to zero.

    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))        {            stream.SetLength(0);            using (var writer = new StreamWriter(stream))            {                if (lines.Length > 0)                {                    for (var i = 0; i < lines.Length - 1; i++)                    {                        writer.WriteLine(lines[i]);                    }                    writer.Write(lines[lines.Length - 1]);                }            }        }    }