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
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Console.WriteLine(Path.Combine(path, "test1"));
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
Examples
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:
string key = "\\\u0066\n"; Console.WriteLine(key);
Example 2:
string path = @"c:\Docs\iodocs\data.txt" // rather than "c:\\Docs\\iodocs\\data.txt"; Console.WriteLine(path);
To include a double quotation mark in an @-quoted string, double it:
Example 3:
string msj = @"""Ahoy!"" the captain cried all hands." // "Ahoy!" the captain cried all hands. Console.WriteLine(msj);
The following example illustrates the effect of defining a regular string literal and a verbatim string literal that contain identical character sequences.
Example 4:
string msj1 = "He said, \"Today this is the last \u0063hance\x0021\""; string msj2 = @"He said, ""Today this is the last \u0063hance\x0021"""; Console.WriteLine(msj1); Console.WriteLine(msj2); // The example displays the following output: // He said, "Today this is the last chance!" // He said, "Today this is the last \u0063hance\x0021"