33

I have the following string, which I want to execute as a process:

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

However, given the presence of quotation marks, I can't insert this string in C# to make it compile, keeping all of the original structure. How should I fix this? It's a little tricky as there are quotation marks within the string.

one noa
  • 345
  • 1
  • 3
  • 10
blade44
  • 447
  • 1
  • 4
  • 7
  • Yup, this is called 'escaping' and usually you prefix the character in question with a backslash (\). – Kieren Johnstone Apr 04 '11 at 15:28
  • 1
    possible duplicate of [In C#, can I escape a double quote in a literal string?](http://stackoverflow.com/questions/1928909/in-c-can-i-escape-a-double-quote-in-a-literal-string) – Nix Apr 04 '11 at 15:31
  • Does this answer your question? [Can I escape a double quote in a verbatim string literal?](https://stackoverflow.com/questions/1928909/can-i-escape-a-double-quote-in-a-verbatim-string-literal) – Liam Nov 27 '19 at 10:48

7 Answers7

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

or

string whatever = @"Rundll32 Printui.dll,PrintUIEntry /ia /K /q /m ""SHARP MX-5500N PS"" /h ""Windows NT x86"" /v 3 /f sn0hwenu.inf";
rsenna
  • 11,775
  • 1
  • 54
  • 60
20

You can put @ in front of the string definition and put two ":

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

You can read more about escaping characters in strings in this article:

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

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
5

you have to escape the quotation marks using \. to have a string that says: Hello "World" you should write "Hello\"World\""

AbdouMoumen
  • 3,814
  • 1
  • 19
  • 28
4
string s = "Rundll32 Printui.dll,PrintUIEntry /ia /K /q /m \"SHARP MX-5500N PS\" /h \"Windows NT x86\" /v 3 /f sn0hwenu.inf";
BrandonZeider
  • 8,014
  • 2
  • 23
  • 20
2

You can also always use Convert.ToChar(34), 34 being the ASCII of ".

for eg:

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

equals:

commit * -m "messBox.Text";
2

Starting with C# 11, it is possible to use three quotes (""") at the beginning and end of a string, instead of just one as usual:

string s = """{ "Id": 1, "Name": "Alex" }""";
Bogdan
  • 21
  • 4
0

Just put in a backslash \ before the quotation marks as needed:

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

The string now contains: This is where you put "your" string