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

前端 未结 9 1128
情歌与酒
情歌与酒 2020-12-17 17:58

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.Fi         


        
相关标签:
9条回答
  • 2020-12-17 18:51

    WriteAllLines writes every single entry in your array and append a newline.
    As you can see, every string is on its own line, this means that your last entry is newline terminated and you see a one more line in file. You could prove this with an hexdecimal dump of the file

    Looking at the source code of WriteAllLines confirms this.
    Internally, it uses the TextWriter.WriteLine(string) method.

    0 讨论(0)
  • 2020-12-17 18:52

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

    File.WriteAllText(file, String.Join("\r\n",correctedLines));
    
    0 讨论(0)
  • 2020-12-17 18:54

    The easiest way for me to do it was usning AppendAllText for last line:

    if ($i -ne $lines.Count - 1){
         $newLines += $lines[$i]
        } else {
         $lastLine = $lines[$i]
    }
    
    [IO.File]::WriteAllLines($file.FullName, $newLines);
    [IO.File]::AppendAllText($file.FullName, $lastLine);
    
    0 讨论(0)
提交回复
热议问题