Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With StreamWriter doesn't work \n (C#)

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.

like image 271
Waronius Avatar asked Nov 12 '12 16:11

Waronius


People also ask

What is the difference between FileStream and StreamWriter?

Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.

What does StreamWriter flush do?

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

Where does StreamWriter Write to?

StreamWriter. WriteLine() method writes a string to the next line to the steam. The following code snippet creates and writes different author names to the stream.

What is the difference between StreamWriter and TextWriter?

TextWriter is an abstract class, which means it cannot be instantiated using the new keyword. From the MSDN documentation: By default, a StreamWriter is not thread safe.


2 Answers

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

like image 194
Alexei Levenkov Avatar answered Oct 17 '22 01:10

Alexei Levenkov


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

change your text as :

       string text = "l1\r\nl2\r\nl3\r\nl5";
like image 24
Yogendra Singh Avatar answered Oct 17 '22 01:10

Yogendra Singh