Is there any way to insert an empty line in a string type variable.

string textFile = "abc";

textFile = textFile + string.Empty;
textFile = textFile + "def";

This is what I'm trying. But the string.Empty has no effect.

This also neither works textFile = textFile + "\n";

Any suggestions?

Dani AI

Generated

A portable way to add a blank line is to use the platform-appropriate newline rather than hard-coding escape sequences. In .NET, Environment.NewLine yields \r\n on Windows and \n on Linux/macOS. When building multi-line text, prefer StringBuilder.AppendLine (call AppendLine() with no arguments to insert an empty line) or compose lines with string.Join. See Environment.NewLine, StringBuilder.AppendLine, and string.Join.

var sb = new StringBuilder();
sb.AppendLine("abc");
sb.AppendLine();          // inserts a blank line
sb.AppendLine("def");
string text = sb.ToString();
// or:
string text2 = string.Join(Environment.NewLine, "abc", "", "def");

If you are sending this to a web page, remember that HTML ignores newline characters. To show empty lines in ASP.NET, either wrap in <pre>, use CSS like white-space: pre-line, or HTML-encode and replace newlines with <br /> before rendering to the page to avoid XSS.

string html = System.Web.HttpUtility.HtmlEncode(text)
    .Replace("\r\n", "<br />")
    .Replace("\n", "<br />");

For file or console output, TextWriter.WriteLine (e.g., StreamWriter or Console) will add the correct newline; calling WriteLine() with no arguments outputs a blank line. See TextWriter.NewLine.

Recommended Answers

All 5 Replies

string.Empty is the empty string, not an empty line. "\n" is a string that contains a newline character. If you want an empty line, you need two newline characters.

So I need to do this

textFile = textFile + "\n\n"; ?

string.Empty is the empty string, not an empty line. "\n" is a string that contains a newline character. If you want an empty line, you need two newline characters.

So I need to do this

textFile = textFile + "\n\n"; ?

Newline characters separate lines.

Thanks got that working...

Newline characters separate lines.

The first newline moves you to the beginning of a new line.
The second newline moves you to the beginning of yet another new line. That way you get an empty line between two "string" lines. If you know how a typewriter works you will get the idea.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.