Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 377
Konrad Viltersten Avatar asked Feb 08 '23 23:02

Konrad Viltersten


2 Answers

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'));
like image 112
Backs Avatar answered Feb 15 '23 10:02

Backs


Instead of using

File.WriteAllText(path, content);

use

File.WriteAllLines(path, content.Split('\n'));
like image 45
Tyler Gaffaney Avatar answered Feb 15 '23 11:02

Tyler Gaffaney