Dot-Net

.NET File.WriteAllLines 在文件末尾留下空行

  • September 25, 2019

當我保存字元串的內容時

$$ $$帶有 System.IO.File.WriteAllLines 的數組,在文件末尾總是留有一個空行。例如:

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

生成文件(不帶下劃線):

a
b
c
_

已經有這樣的話題:.Net File.WriteAllLines 中的空行,是錯誤嗎?,但作者說“我認為我的數據有問題,這是我的問題,但不是 WritAllLines”,它被關閉為“過於本地化”(?!?)。

這是一個錯誤?我怎樣才能輕鬆擺脫它(現在我只是在再次讀取文件時忽略它)?

WriteAllLines方法將寫出數組中的每一行,然後是換行符。這意味著您將始終在文件中獲得此“空行”。

您連結的文章中的要點是,在執行時ReadAllLines認為一行是由換行符終止的字元。因此,當您對剛剛編寫的文件使用 read 方法時,您應該得到完全相同的行。

如果您以不同的方式讀取文件,那麼您將不得不自己處理換行符。

本質上,您所看到的是預期行為。

正如其他人指出的那樣,這就是它的工作原理。這是一種無需額外換行符的方法:

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]);
           }
       }
   }
}

用法:

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

寫道:

一個enter
_enter
C

引用自:https://stackoverflow.com/questions/11689337