使用 File.WriteAllText(string,string) 时没有换行符

Kon*_*ten 3 c# file line-breaks

我注意到我使用下面的代码创建的文件中没有换行符。在我也存储文本的数据库中,存在这些文本。

string story = "Critical error occurred after " 
  + elapsed.ToString("hh:mm:ss") 
  + "\n\n" + exception.Message;
File.WriteAllText(path, story);
Run Code Online (Sandbox Code Playgroud)

因此,经过一些简短的谷歌搜索后,我了解到我应该使用Environment-NewLine而不是文字\n来引用新行。所以我添加了如下所示。

string story = "Critical error occurred after " 
  + elapsed.ToString("hh:mm:ss") 
  + "\n\n" + exception.Message;
  .Replace("\n", Environment.NewLine);
File.WriteAllText(path, story);
Run Code Online (Sandbox Code Playgroud)

尽管如此,输出文件中没有换行符。我错过了什么?

Bac*_*cks 5

尝试StringBuilder的方法-这是更具可读性,你不需要记住Environment.NewLine\n\r\n

var sb = new StringBuilder();

string story = sb.Append("Critical error occurred after ")
               .Append(elapsed.ToString("hh:mm:ss"))
               .AppendLine()
               .AppendLine()
               .Append(exception.Message)
               .ToString();
File.WriteAllText(path, story);
Run Code Online (Sandbox Code Playgroud)

简单的解决方案:

string story = "Critical error occurred after " 
  + elapsed.ToString("hh:mm:ss") 
  + Environment.NewLine + exception.Message;
File.WriteAllLines(path, story.Split('\n'));
Run Code Online (Sandbox Code Playgroud)