28

How to escape the character \ in C#?

1
  • 5
    For future reference, when searching in Google, the magic words for this sorta thing are "escape" or "escaping" :) Commented Apr 2, 2013 at 15:35

7 Answers 7

62

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.

Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

He didn't say he wanted it as a char, he said he wanted to know how to write it.
@Romoku: Well, the question talks about char rather than string, and uses single quotes in the example. I agree it could be clearer though.
@JonSkeet Well I edited in the char to provide a complete answer.
@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.
@JonSkeet I figured @"\"[0] was close enough. Probably not very efficient.
1

use double backlash like so "\"

"\\"

cause an escape

Comments

1

If you want to output it in a string, you can write "\\" or as a character, you can write '\\'.

Comments

1

Escape it: "\\"

or use the verbatim syntax: @"\"

1 Comment

The @ is for verbatim, not global escape. Verbatim strings contain even the newline characters, etc.
1

Double escape it. Escape escape = no escape! \\

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.