Blog Archives

Newlines in a Textbox

I have been implementing some enhancements to an in-house test client application my company uses. It is a Windows Forms application which I wanted to add a textbox to for adding notes to test cases. The Textbox was multi-line and accepts carriage returns. The content of the textbox is then serialized (along with other values) and saved to a file. The file can then be retrieved later, deserialized and used to re-populate the form.

I noticed that whilst the newlines were saved in the file, when re-populating the textbox, the newlines were not displayed and all of the text was on one line. Debugging the app indicated that when reading the file, the newlines were still in place and indicated by \n in the Watch window. After a bit of research, it seems I needed to replace the \n instances with the correct newline characters recognised by C# using the Environment.Newline function. In the end I wrapped this up in a small extension method.

internal static string PreserveFormatting(this string source)
     return source.Replace(((char)10).ToString(), Environment.NewLine);