Search code examples
c#streamwriter

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


Solution

  • 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 ;...