Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...