[英]How to Escape Double Quote in Multline Literal String
我正在构建一个 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\">
上 我可以不将 \ 与文字一起使用吗? 我有哪些选择?
您只需使用 2 个连续的双引号 ( ""
):
string s = @"Porky The Pig said, ""That's all, Folks!""...";
但是您可能想要使用合适的模板引擎,例如(但绝不限于):
与滚动你自己的相比,它们几乎肯定不会受到各种注入攻击的影响。
您可能会发现在 HTML 文件中创建 HTML 比连接字符串更可取。 尝试以下操作:
创建一个 Windows Forms App (.NET Framework)
对比 2019 :
打开解决方案资源管理器
打开属性 Window
添加文件夹(名称:Html)
添加 HTML 文件
创建一个class (名称: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");
资源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.