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);


Posted on July 18, 2012, in programming and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: