How to write single back slash in string in C#


Solution 1

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: "\\Tasks" or @"\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.

Solution 2

Do not try to build path names concatenating strings. Use the Path.Combine method

The Path class contains many useful static methods to handle strings that contains paths, filenames and extensions. This class is very useful to avoid many common errors and also allows to code for a better portability between operating systems (“\” on win, “/” on Linux)

The Path class is defined in the namespace System.IO.
You need to add using System.IO; to your code


String literals can contain any character literal. Escape sequences are included. The following example uses escape sequence \\ for backslash, \u0066 for the letter f, and \n for newline.

Example 1:

Example 2:

To include a double quotation mark in an @-quoted string, double it:

Example 3:

The following example illustrates the effect of defining a regular string literal and a verbatim string literal that contain identical character sequences.

Example 4:

how to write single back slash in string in C#
4.7 (94%) 10 votes