If you want an actual backslash in the string or regex, you have to write two: \\ . If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level.
In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal. For example, the following value is used to represent a matching value of & only: ?
You just need to escape it: char c = '\\'; Or you could use the Unicode escape sequence: char c = '\u005c';
You can use '\\' to refer to a single backslash in a regular expression. However, backslash is also an escape character in Java literal strings. To make a regular expression from a string literal, you have to escape each of its backslashes.
The backslash ("\"
) character is a special escape character used to indicate other special characters such as new lines (\n
), tabs (\t
), or quotation marks (\"
).
If you want to include a backslash character itself, you need two backslashes or use the @
verbatim string:
var s = "\\Tasks";
// or
var s = @"\Tasks";
Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.
Generally speaking, most C# .NET developers tend to favour using the @
verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.
That all said, in this case, I would actually recommend you use the Path.Combine
utility method as in @lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.
To escape the backslash, simply use 2 of them, like this:
\\
If you need to escape other things, this may be helpful..
There is a special function made for this Path.Combine()
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");
Just escape the "\"
by using + "\\Tasks"
or use a verbatim string like @"\Tasks"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With