Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

When I'm saving content of the String[] array with System.IO.File.WriteAllLines, at the end of a file is always left a blank line. For example:

System.IO.File.WriteAllLines(Application.dataPath + "/test.txt",["a", "b", "c"]);

Produces file (without underscore):

a
b
c
_

There was already such topic: Empty line in .Net File.WriteAllLines, is a bug? , but autor said that "I think there are something wrong with my data,that's my problem but not the WritAllLines" and it was closed as "too localized" (?!?).

It's a bug? How can I easily get rid of it (for now I'm just ignoring it when reading file again)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...