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

No line breaks when using File.WriteAllText(string,string)

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

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

所以经过一些 short googling 我了解到我应该使用 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);

仍然,输出文件中没有换行符。我错过了什么?

尝试 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);

简单的解决方案:

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

您可以像下面的代码那样使用 WriteLine() 方法

   using (StreamWriter sw = StreamWriter(path)) 
        {
            string story = "Critical error occurred after "  +elapsed.ToString("hh:mm:ss");
            sw.WriteLine(story);   
            sw.WriteLine(exception.Message); 
        }

而不是使用

File.WriteAllText(path, content);

使用

File.WriteAllLines(path, content.Split('\n'));

WriteAllText 去除换行符,因为它不是文本。