[c#] How do I write a backslash (\) in a string?

I want to write something like this C:\Users\UserName\Documents\Tasks in a textbox:

txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\Tasks";

I get the error:

Unrecognized escape sequence.

How do I write a backslash in a string?

This question is related to c# string winforms

The answer is


even though this post is quite old I tried something that worked for my case .

I wanted to create a string variable with the value below:

21541_12_1_13\":null

so my approach was like that:

  • build the string using verbatim

    string substring = @"21541_12_1_13\"":null";

  • and then remove the unwanted backslashes using Remove function

    string newsubstring = substring.Remove(13, 1);

Hope that helps. Cheers


Just escape the "\" by using + "\\Tasks" or use a verbatim string like @"\Tasks"


txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";

Put a double backslash instead of a single backslash...


There is a special function made for this Path.Combine()

var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");

To escape the backslash, simply use 2 of them, like this: \\

If you need to escape other things, this may be helpful..


The previous answer is correct but in this specific case I would recommend using the System.IO.Path.Combine method.

You can find more details here: http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx