开发者

C# won't escape "\"? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to use “\” in a string without making it an escape sequence - C#?

Why is it giving me an error in C# when I use a string like: "\themes\开发者_Go百科default\layout.png"? At the "d" and "l" location? It says unrecognized escape sequence. And how do I stop it from giving me an error when I use: "\"?

Thans


You need to escape it with an additional \:

string value = "\\themes\\default\\layout.png";

or use the @ symbol:

string value = @"\themes\default\layout.png";

which will avoid you from doubling all \.

Or if you are dealing with paths (which is what it seems you are) you could use the Path.Combine method:

string value = Path.Combine(@"\", "themes", "default", "layout.jpg");


You're using a backslash to escape 't' and 'd'. If you want to escape the actual backslash you need to do so:

"\\themes\\default\\layout.png"


"Regular" string literals treat the \ character as a special character, used for escape sequences to insert quickly special characters in strings - \n, for example, is used to insert the newline character, \" is used to insert the " character without terminating the string, and so on.

Because of this, to insert a backslash into a "normal" string you have to insert the corresponding escape sequence, which, unsurprisingly, is \\; you would then write in your case:

"\\themes\\default\\layout.png"

Failing to escape the backslashes will result in weird results or errors like the ones you got, since the compiler will try to interpret the couple backslash-letter that follows it as an escape sequence; if such sequence is defined you'll get unwanted characters (e.g. the first \t is escaped to a tab character), if it's not (like \l) you'll get an error about an undefined escape sequence.

Another option, if you don't need to escape any character, is to use the so-called "verbatim" strings literals: if you prefix the string with an @ character the escape sequences will be disabled, and the string you write will be taken verbatim by the compiler. The only exception to this rule is for quotes, that can be inserted inside the verbatim string via the "quote escape sequence", i.e. "". In your case you would write:

@"\themes\default\layout.png"

For more info about regular vs verbatim string literals have a look at their documentation.


The backslash is treated as an escape character. Either escape the backslash itslef in the string like so:

"\\themes\\default\\layout.png"

or disable escaping altogether using a verbatim string literal:

@"\themes\default\layout.png"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜