Reputation: 21271
What's the best way to create multi-line string in C#?
I know the following methods:
var result = new StringBuilder().AppendLine("one").AppenLine("two").ToString()
looks too verbose.
var result = @"one
two"
looks ugly and badly formatted.
Upvotes: 8
Views: 14011
Reputation: 14485
Riffing off of what @codymanix said, you could place the long multiline string in a resource file. This can be easier for certain deployment scenarios since the text "file" will be included in your DLL / EXE.
Upvotes: 1
Reputation: 29468
You should not define large strings in your source code. You should define it in an external text file:
string s = File.OpenText("myfile.txt").ReadToEnd();
Upvotes: 1
Reputation: 896
I'd say it depends on what You need...
But to simplify it I would go with:
var s = new StringBuilder();
s.Append("one");
s.Append("two");
s.ToString();
But since we don't know what You need it for. It's pretty difficult to give better hints
Upvotes: 2
Reputation: 57182
What about this:
var result = string.Join(Environment.NewLine, new string[]{
"one",
"two"
});
It's a bit painful and possibly an overkill, but it gives the possibility to preserve the lines separation in your code.
To improve things a little, you could use an helper method:
static string MultiLine(params string[] args) {
return string.Join(Environment.NewLine, args);
}
static void Main(string[] args) {
var result = MultiLine(
"one",
"two"
);
}
Upvotes: 24
Reputation: 102468
"Best" is a very very open ended point.
Are you after :
All of those make a big difference as to the "best" way of doing something.
Upvotes: 2
Reputation: 1164
Sometimes you need more than one line. I use Environment.NewLine but I placed it in a method to multiply it. :)
private string newLines(int multiplier)
{
StringBuilder newlines = new StringBuilder();
for (int i = 0; i < multiplier; i++)
newlines.Append(Environment.NewLine);
return newlines.ToString();
}
Upvotes: 0
Reputation: 545528
What about this?
var result = "one\ntwo";
If you're fussy about OS-specific line endings, use Format
:
var result = String.Format("one{0}two", Environment.NewLine);
(Well, “fussy” isn’t the right word: when dealing with text files, OS-specific line endings are often desired or even necessary, when dealing with legacy software.)
Upvotes: 12