Unrecognized escape sequence for path string containing backslashes

C#.NetStringPathEscaping

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKjensenView Question on Stackoverflow
Solution 1 - C#BrandonView Answer on Stackoverflow
Solution 2 - C#JoshView Answer on Stackoverflow
Solution 3 - C#Piotr CzaplaView Answer on Stackoverflow
Solution 4 - C#Scott WeinsteinView Answer on Stackoverflow
Solution 5 - C#Bob KaufmanView Answer on Stackoverflow