How to escape the character \
in C#?
Asked
Active
Viewed 1.1e+01k times
7 Answers
61
You just need to escape it:
char c = '\\';
Or you could use the Unicode escape sequence:
char c = '\u005c';
See my article on strings for all the various escape sequences available in string/character literals.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
13
You can escape a backslash using a backslash.
//String
string backslash = "\\";
//Character
char backslash = '\\';
or
You can use the string literal.
string backslash = @"\";
char backslash = @"\"[0];

Dustin Kingen
- 20,677
- 7
- 52
- 92
-
1He didn't say he wanted it as a char, he said he wanted to know how to write it. – Dustin Kingen Apr 01 '13 at 17:17
-
@Romoku: Well, the question talks about char rather than string, *and* uses single quotes in the example. I agree it could be clearer though. – Jon Skeet Apr 01 '13 at 17:18
-
1@JonSkeet Well I edited in the char to provide a complete answer. – Dustin Kingen Apr 01 '13 at 17:19
-
@Romoku: You might want to get rid of the `@'\'` bit as it's invalid. I had a brain-fart when I included it. Also, the `@` makes it a *verbatim* string literal, as opposed to a *plain* string literal without - both are string literals. – Jon Skeet Apr 01 '13 at 17:20
-
@JonSkeet I figured `@"\"[0]` was close enough. Probably not very efficient. – Dustin Kingen Apr 01 '13 at 17:25
1
If you want to output it in a string, you can write "\\"
or as a character, you can write '\\'
.

Umar Farooq Khawaja
- 3,925
- 1
- 31
- 52
1
Double escape it. Escape escape = no escape! \\

Joshua Grosso Reinstate CMs
- 2,086
- 2
- 15
- 32

Justin
- 6,373
- 9
- 46
- 72
1
Escape it: "\\"
or use the verbatim syntax: @"\"

Dave Clausen
- 1,302
- 1
- 12
- 23
-
The `@` is for verbatim, not global escape. Verbatim strings contain even the newline characters, etc. – Umar Farooq Khawaja Apr 01 '13 at 17:19
1
To insert a backslash, you need to type it twice:
string myPath = "C:\\Users\\YourUser\\Desktop\\YourFile.txt";
The string myPath
should now contain: C:\Users\YourUser\Desktop\YourFile.txt

TheProgrammer
- 58
- 10