Search code examples
c#fileline-breaks

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


I noticed that there are no line breaks in the file I'm creating using the code below. In the database, where I also store the text, those are present.

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

So after some short googling I learned that I'm supposed to refer to the new lines using Environment-NewLine rather than the literal \n. So I added that as shown below.

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

Still, no line breaks in the output file. What Am I missing?


Solution

  • Try StringBuilder methods - it's more readable and you don't need to remember about Environment.NewLine or \n\r or \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);
    

    Simple solution:

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