Konrad Viltersten
Konrad Viltersten

Reputation: 39118

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?

Upvotes: 4

Views: 11305

Answers (4)

Tyler Gaffaney
Tyler Gaffaney

Reputation: 86

Instead of using

File.WriteAllText(path, content);

use

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

Upvotes: 4

Smard
Smard

Reputation: 1

WriteAllText strips newlines, because it is not text.

Upvotes: -2

Backs
Backs

Reputation: 24903

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'));

Upvotes: 6

Arash
Arash

Reputation: 885

You can use WriteLine() method like below code

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

Upvotes: 0

Related Questions