19

I have a problem with the C# Stream Writer. I use the following Code:

//Constructor
public EditorTXTFile
{
   FileStream f = File.Create(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt");
   f.Close();
}

//Function AddText
public void AddLogFileText(string text)
{         
   string text = "l1\n\rl2\n\rl3\n\nl5";

   StreamWriter writer = new StreamWriter(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt", true);
   writer.Write(text);         

   writer.Close();
}

When I open Output.txt it shows for \n or \r a █(which means not showable symbol) and the whole string is in one line... Later should the text hand over the function, so I can't write the text with .WriteLine because I don't know if the actual string is on the same line or in a new line.

What make I wrong?

Thanks for any help.

Waronius
  • 363
  • 2
  • 4
  • 10

6 Answers6

37

Use Environment.NewLine as line separator or "\r\n" if you want to do it by hand.

Omar
  • 16,329
  • 10
  • 48
  • 66
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 2
    The beauty of `Environment.NewLine` is that you don't have to worry about the correct combo of `\r\n` for the particular environment in which your code is running. – Michael Sallmen Nov 12 '12 at 16:11
2

Line Separator(newLine) is \r\n not \n\r,

change your text as :

       string text = "l1\r\nl2\r\nl3\r\nl5";
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

Try string text = @"l1\n\rl2\n\rl3\n\nl5";. To prevent character stuffing.

Michael Sallmen
  • 728
  • 5
  • 13
0

This is binary format:

writer.Write(text); 

This is line sequential format:

writer.WriteLine(text); 

You have to use WriteLine format...

pb2q
  • 58,613
  • 19
  • 146
  • 147
0

You can use Environment.NewLine like this:

streamWriter.Write(String.Concat(Enumerable.Repeat(Environment.NewLine, n).ToArray()));
Andrei Marincas
  • 446
  • 5
  • 13
0

i tried to write a class and seprate "\n"s but i found rich text box!!

yeah! it works:

        RichTextBox rch = new RichTextBox();
        rch.Text = cmn;
        foreach (string l in rch.Lines)
            strw.WriteLine(l);
Aref Khandan
  • 189
  • 5