How to write single back slash in string in C#
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:
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.
Do not try to build path names concatenating strings. Use the Path.Combine method
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
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
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.
string key = "\\\u0066\n";
string path = @"c:\Docs\iodocs\data.txt" // rather than "c:\\Docs\\iodocs\\data.txt";
To include a double quotation mark in an @-quoted string, double it:
string msj = @"""Ahoy!"" the captain cried all hands." // "Ahoy!" the captain cried all hands.
The following example illustrates the effect of defining a regular string literal and a verbatim string literal that contain identical character sequences.
string msj1 = "He said, \"Today this is the last \u0063hance\x0021\"";
string msj2 = @"He said, ""Today this is the last \u0063hance\x0021""";
// The example displays the following output:
// He said, "Today this is the last chance!"
// He said, "Today this is the last \u0063hance\x0021"