C# – appending a character with double quotes using stringbuilder in c#

asp.netc++stringbuilder

Hi I want to append the line

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

to a text file but I am stuck at the "C#" , "WebForm1.aspx.cs" and "WebApplication1.WebForm1" part my code is as below

 public string HeaderContent1()
 {
     var sb = new StringBuilder();
     sb.Append("<%@ Page Language=");
     sb.Append("c#");// prints only c#
     sb.Append("AutoEventWireup=");
     sb.Append("true");
     sb.Append("CodeBehind=");
     sb.Append("WebForm1.aspx.cs");// prints only WebForm1.aspx.cs I want with double quotes
     sb.Append("WebApplication1.WebForm1");// prints only WebApplication1.WebForm1 I want with double quotes
     sb.Append("%>");

     sb.AppendLine();
     sb.Append("<html>");
     sb.AppendLine();// which is equal to Append(Environment.NewLine);
     sb.Append("<head>");
     sb.AppendLine();
     sb.Append("<h1>New File header</h1>");
     sb.AppendLine(); // which is equal to Append(Environment.NewLine);
     sb.Append("</head>");
     sb.AppendLine();
     sb.Append("<body>");
     sb.AppendLine(); // which is equal to Append(Environment.NewLine);
     sb.Append("<h2> New File Body</h2>");
     sb.AppendLine();

     sb.Append("</body>");
     sb.AppendLine();

     sb.Append("</html>");
     sb.AppendLine();
}

Best Solution

You have a couple options when trying to use a quote inside a quoted string.

You can escape the quotations:

sb.Append("\"WebForm1.aspx.cs\"");

Or use a verbatim symbol:

sb.Append(@"""WebForm1.aspx.cs""");

You could eliminate the StringBuilder altogether:

var page = "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"WebForm1.aspx.cs\" Inherits=\"WebApplication1.WebForm1\" %><html>\r\n<head>\r\n<h1>New File header</h1>\r\n</head>\r\n<body>\r\n<h2> New File Body</h2>\r\n</body>\r\n</html>";
Related Question