C# Tips N Tricks: Saving Character Literals as String Characters

We have a requirement that when saving a specific type of string to the database it needs to save newline characters as a string (“\n”) not the character literal (‘\n’). It should have been straight forward but I found myself spinning in circles and decided to make a note on what the final code looked like.

CSHTML View:

	@Html.TextArea("Message", Model.Message, new { maxlength = 5000 })

Saving to DB:

      item.Message = model.Message.Replace("\r\n","\\n");

Pulling from DB:

      if (item != null)
      {
        Message = item.Message.ToStringOrEmpty().Replace("\\n", "\r\n");
      }
      if (Message.IsNullOrEmpty())
        Message = "Message goes here.\r\n\r\nSincerely,";

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s