如何在多行文字字符串中转义双引号



我正在构建一个HTML字符串。我想让它多行,这样我就可以阅读了,但我似乎不知道如何避开双引号。我使用string = @"bla"作为字符串文字,以允许多行,但当我似乎不能使用反斜杠来转义双引号时。

这是我的。。。

string output;
output = @"<html>
<head>
<style>
th, tr, td { padding-left: 5px; }
</style>    
</head>
<body>
<table>
<tr>
<td colspan="2">";

它挂在<td colspan="2">上了。我可以不把\和文字一起使用吗?我有什么选择?

您只需使用两个连续的双引号(""(:

string s = @"Porky The Pig said, ""That's all, Folks!""...";

但是您可能想要使用一个合适的模板引擎,例如(但绝不限于(:

  • 字符串模板:https://www.stringtemplate.org/
  • Handlebars.Net:https://github.com/Handlebars-Net/Handlebars.Net
  • DotLiquid:http://dotliquidmarkup.org/
  • 斯克里班:https://github.com/scriban/scriban

他们几乎肯定不会像你自己那样容易受到各种注入攻击。

您可能会发现在HTML文件中创建HTML比串联字符串更可取。尝试以下操作:

创建Windows窗体应用程序(.NET Framework(

VS 2019

打开解决方案浏览器

  • 在VS菜单中,单击查看
  • 选择解决方案资源管理器

打开属性窗口

  • 在VS菜单中,单击查看
  • 选择属性窗口

添加文件夹(名称:Html(

  • 在解决方案资源管理器中,右键单击<项目名称>
  • 选择添加
  • 选择新建文件夹。重命名为所需名称(例如:Html(

添加HTML文件

  • 在解决方案资源管理器中,右键单击您创建的文件夹(例如:Html(
  • 选择添加
  • 选择新建项目
  • 在左侧的Visual C#项目下,单击Web
  • 选择HTML页面(名称:HTMLPage1.HTML(
  • 单击"添加">
  • 在解决方案资源管理器中,单击HTML页面(例如:HTMLPage1.HTML(
  • 在"属性"窗口中,设置以下属性:生成操作:嵌入式资源

创建一个类(名称:HelperLoadResource.cs(

添加以下使用语句

  • using System;
  • using System.Text;
  • using System.IO;
  • using System.Reflection;

HelperLoadResource

注意:以下代码来自本文。

public static class HelperLoadResource
{
public static string ReadResource(string filename)
{
//use UTF8 encoding as the default encoding
return ReadResource(filename, Encoding.UTF8);
}
public static string ReadResource(string filename, Encoding fileEncoding)
{
string fqResourceName = string.Empty;
string result = string.Empty;
//get executing assembly
Assembly execAssembly = Assembly.GetExecutingAssembly();
//get resource names
string[] resourceNames = execAssembly.GetManifestResourceNames();
if (resourceNames != null && resourceNames.Length > 0)
{
foreach (string rName in resourceNames)
{
if (rName.EndsWith(filename))
{
//set value to 1st match
//if the same filename exists in different folders,
//the filename can be specified as <folder name>.<filename>
//or <namespace>.<folder name>.<filename>
fqResourceName = rName;
//exit loop
break;
}
}
//if not found, throw exception
if (String.IsNullOrEmpty(fqResourceName))
{
throw new Exception($"Resource '{filename}' not found.");
}
//get file text
using (Stream s = execAssembly.GetManifestResourceStream(fqResourceName))
{
using (StreamReader reader = new StreamReader(s, fileEncoding))
{
//get text
result = reader.ReadToEnd();
}
}
}
return result;
}
}

用法

//get HTML as string
string html = HelperLoadResource.ReadResource("HTMLPage1.html");

资源

  • 如何读取嵌入的资源文本文件

最新更新