Kjensen
Kjensen

Reputation: 12374

Unrecognized escape sequence for path string containing backslashes

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?

Upvotes: 104

Views: 304084

Answers (5)

Scott Weinstein
Scott Weinstein

Reputation: 19117

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#.

Upvotes: 13

Josh
Josh

Reputation: 16532

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";

Upvotes: 31

Bob Kaufman
Bob Kaufman

Reputation: 12825

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 "\\"

Upvotes: 5

Brandon
Brandon

Reputation: 69993

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";

Upvotes: 250

Piotr Czapla
Piotr Czapla

Reputation: 26532

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

Upvotes: 14

Related Questions