如何在字符串中使用带引号的内容?

33

我有以下字符串,我想将其作为进程执行:

Rundll32 Printui.dll,PrintUIEntry /ia /K /q /m "SHARP MX-5500N PS" /h "Windows NT x86" /v 3 /f sn0hwenu.inf

然而,由于存在引号,我不能将此字符串插入到C#中进行编译,同时保留所有原始结构。我该如何解决?这有点棘手,因为字符串中包含引号。


是的,这被称为“转义”,通常您需要在问题字符前加上反斜杠(\)。 - Kieren Johnstone
这个回答解决了你的问题吗?我能在verbatim字符串字面量中转义双引号吗? - Liam
7个回答

41
string whatever = "Rundll32 Printui.dll,PrintUIEntry /ia /K /q /m \"SHARP MX-5500N PS\" /h \"Windows NT x86\" /v 3 /f sn0hwenu.inf";
或者
string whatever = @"Rundll32 Printui.dll,PrintUIEntry /ia /K /q /m ""SHARP MX-5500N PS"" /h ""Windows NT x86"" /v 3 /f sn0hwenu.inf";

20
你可以在字符串定义前面加上@,然后再放两个"
string myString = @"Rundll32 Printui.dll,PrintUIEntry /ia /K /q /m ""SHARP MX-5500N PS"" /h ""Windows NT x86"" /v 3 /f sn0hwenu.inf"

您可以在这篇文章中了解有关字符串中转义字符的更多信息:

http://www.yoda.arachsys.com/csharp/strings.html


5

您需要使用\来转义引号。如果想要一个字符串,内容为:Hello "World",您应该写成"Hello\"World\""


4
string s = "Rundll32 Printui.dll,PrintUIEntry /ia /K /q /m \"SHARP MX-5500N PS\" /h \"Windows NT x86\" /v 3 /f sn0hwenu.inf";

2
您始终可以使用Convert.ToChar(34)进行转换,其中34是引号的ASCII码。

例如:
gitInfo.Arguments = @"commit * " + "-m" + Convert.ToChar(34) + messBox.Text + Convert.ToChar(34);

等于:

commit * -m "messBox.Text";

2

从C# 11开始,可以使用三个引号(""")来代替通常的一个引号,放在字符串的开头和结尾:

string s = """{ "Id": 1, "Name": "Alex" }""";

0

只需在需要的引号前加上反斜杠\

string yourString = "This is where you put \"your\" string";

字符串现在包含:这是你放置“你的”字符串的地方


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接