Ardahan Kisbet
Ardahan Kisbet

Reputation: 659

How to write strings which is already have new line character using streamwriter in C#?

I have a string which has \n character in some parts. I want to write that string into text file. I try Write and WriteLine method of streamwriter and in both it writes in a single line. So, is there any simple way to write this string using its new line character or should a split it into array by \n character.

Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
        sfd.Filter = "g-code|*.gcode;";
        if (sfd.ShowDialog() == true)
        {
            string path = System.IO.Path.GetFullPath(sfd.FileName);
            System.IO.StreamWriter writer = new System.IO.StreamWriter(sfd.OpenFile());
            writer.Write(GcodeTxt);
            writer.Dispose();
            writer.Close();
            MessageBox.Show("File is saved.", "Saved", MessageBoxButton.OK, MessageBoxImage.Information);
        }

Sample GcodeTxt:"G21;metric is good!\n G90 ;absolute positioning\n T0 ;select new extruder\n G28 ;go home\n G92 E0 ;set extruder home\n M104 S73.0 ;set temperature\n"

And the result is;

enter image description here

Upvotes: 3

Views: 2979

Answers (4)

Visual Vincent
Visual Vincent

Reputation: 18320

Windows Notepad reads only CrLf (Carriage return + Line feed) line endings, which is \r\n. If you put only a line feed character (\n) then Notepad will render it as if it were written in a single line.

Try opening your file in something like Notepad++ and it should look as you want it to.

To write a Carriage return + Line feed, use Environment.NewLine instead.

Upvotes: 2

Glenn Ferrie
Glenn Ferrie

Reputation: 10410

The answers above are accurate. However, you should also consider using StreamWriter.WriteLine instead of StreamWriter.Write when you want to insert a newline.

https://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline(v=vs.110).aspx

Upvotes: 0

usr
usr

Reputation: 171216

Fix the line separator in your strings to match what the platform expects. Windows expects \r\n. Use Environment.NewLine instead of "\n". Your string has been generated in the wrong way. Fix the way it is being built.

Upvotes: 2

omerts
omerts

Reputation: 8838

Your GcodeTxt probably has the \n formatted as a regular string and not a special character. Even if you add \r\n to your text, it will just get formatted as regular string chars.

Use Environment.NewLine instead of \n for cross env newlines: (@"G21;metric is good!" + Environment.NewLine + @" G90 ;...

Upvotes: 2

Related Questions