Stav Alfi
Stav Alfi

Reputation: 13923

How do I write the escape char '\' to code

How to escape the character \ in C#?

Upvotes: 28

Views: 112230

Answers (7)

TheProgrammer
TheProgrammer

Reputation: 58

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

Upvotes: 1

Justin
Justin

Reputation: 6549

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

Upvotes: 1

Dustin Kingen
Dustin Kingen

Reputation: 21245

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

Upvotes: 13

Dave Clausen
Dave Clausen

Reputation: 1320

Escape it: "\\"

or use the verbatim syntax: @"\"

Upvotes: 1

Umar Farooq Khawaja
Umar Farooq Khawaja

Reputation: 3987

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

Upvotes: 1

Prakash Chennupati
Prakash Chennupati

Reputation: 3226

use double backlash like so "\"

"\\"

cause an escape

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500375

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.

Upvotes: 62

Related Questions