102

The following code generates a compiler error about an "unrecognized escape sequence" for each backslash:

string foo = "D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

I guess I need to escape backslash? How do I do that?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Kjensen
  • 12,447
  • 36
  • 109
  • 171

5 Answers5

245

You can either use a double backslash each time

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

or use the @ symbol

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
Brandon
  • 68,708
  • 30
  • 194
  • 223
  • This also helped to resolve an Html.TextBoxFor issue that I was having. Using the @ before the regular expression resolved the Unrecognized escape sequence, where the double backslash failed. – Joshua Feb 27 '17 at 20:37
31

Try this:

string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";

The problem is that in a string, a \ is an escape character. By using the @ sign you tell the compiler to ignore the escape characters.

You can also get by with escaping the \:

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Josh
  • 16,286
  • 25
  • 113
  • 158
  • 4
    FWIW and to help Googlebot, the term for @"" is a "verbatim string literal". Though I've also heard it referred to as just "string literal", that technically includes the "regular string literal" of just "". http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx – Mark Brackett Aug 19 '09 at 22:07
14
var foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
Piotr Czapla
  • 25,734
  • 24
  • 99
  • 122
12

If your string is a file path, as in your example, you can also use Unix style file paths:

string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";

But the other answers have the more general solutions to string escaping in C#.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Scott Weinstein
  • 18,890
  • 14
  • 78
  • 115
5
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

This will work, or the previous examples will, too. @"..." means treat everything between the quote marks literally, so you can do

@"Hello
world"

To include a literal newline. I'm more old school and prefer to escape "\" with "\\"

Bob Kaufman
  • 12,864
  • 16
  • 78
  • 107