tags:

views:

1741

answers:

7

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

I get a compile error "Unrecognized escape sequence" for each backslash.

I guess I need to escape backslash - how?

+4  A: 
var foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
Piotr Czapla
On a minor note, a " is then escaped like ""
flq
Though correct, it doesn't excactly answer the question.
Tor Haugen
+6  A: 

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";
Josh
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
+13  A: 

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
Hm. Four answers to a trivial question, and only one got it entirely right..
Tor Haugen
+1  A: 
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
+1  A: 

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#

Scott Weinstein
A: 

You failed to use Google.

Search for "C# escape backslash", and the answer comes up quickly, validating what other posters have said: either use "\\", or use @ to take the string literally.

abelenky
Why the down vote? I both provide the answer, and teach the OP to fish for himself. The downvote seems rude. :(
abelenky
That could be the answer to 75% of questions on SO (Just fukcing google it). Part of the purpose of SO is, that when you google for something programming related - SO shows up. Now it does for this subject too.
Kjensen
Kjensen: I don't think the internet needs the same question answered multiple times on different sites. You'll do yourself a favour by learning to research.
Noon Silk
A: 

hey if i escape "\" with "\" it stores the value as "\" itself in my string... pl help me out...

eg:

string cns=".\SQLEXPRESS";

i gave as

string cns=".\SQLEXPRESS" OR @".\SQLEXPRESS"

both stores my cns value as ".\SQLEXPRESS"

pl help me out...

Sairam