Sign up for our newsletter and receive a free copy of our book .NET Web Application Logging Essentials
"What a great idea, ELMAH (Error Logging) for .NET in the cloud."
Convert multiline text to a verbatim C# string
We have all been there. We need to insert a multi-line string into a C# program but want to keep this nicely formatted. There are multiple ways of doing this. You can embed each line in "
characters and add a +
in the end. Or you can use a C# verbatim string by adding a @
in front of the string and let it spread across multiple lines. Converting a multi-line text to a verbatim string will require you to make a lot of manual corrections to the string, like converting single quotes to double quotes and more.
With elmah.io's free multi-line text to C# verbatim string converter, you simply input a string in the field above and let us do the magic of converting it to C#. You can copy the end result and paste it directly into the code. You don't need to worry about anyone intercepting your text, since everything is converted directly in the browser.
We monitor your websites for crashes and availability. This helps you get an overview of the quality of your applications and to spot trends in your releases.
We notify you when errors starts happening using Slack, Microsoft Teams, mail or other forms of communication to help you react to errors before your users do.
We help you fix bugs quickly by combining error diagnostic information with innovative quick fixes and answers from Stack Overflow and social media.
When needing to store multi-line strings in C# you have a range of different options. The only usually seen is having newlines characters within the string like this:
var lines = "a\nstring\nwith\nmultiple\nlines";
Storing text like this works but it is not very readable. An alternative is to split the string into multiple strings:
var lines = "a\n"
+ "string\n"
+ "with\n"
+ "multiple\n"
+ "lines";
More readable for sure but still contain unnessecary characters. Developers sometimes fix this by using the Join
method:
var lines = string.Join(
Environment.NewLine,
"a",
"string",
"with",
"multiple",
"lines");
The best solution in C# is to use the verbatim string literal @
:
var lines = @"a
string
with
multiple
lines";
If you need to build more complex strings the StringBuilder
class offer some help:
var sb = new StringBuilder();
sb.AppendLine("a");
sb.AppendLine("string");
sb.Append("wi").AppendLine("th");
sb.AppendLine("multiple");
sb.AppendLine("lines");
var lines = sb.ToString();
As you can see, there are a lot of ways of handling multi-line strings in C#. Our favorite is using the verbatim string literal which you can get help generating using this tool.