Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add backslash to string

I have a path and I want to add to it some new sub folder named test. Please help me find out how to do that. My code is :

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
 Console.WriteLine(path+"\test");

The result I'm getting is : "c:\Users\My Name\Pictures est"

Please help me find out the right way.

like image 806
misha312 Avatar asked Jun 03 '13 14:06

misha312


People also ask

How do you add a backslash to a string in Java?

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.

How do you add a backslash to a string in Python?

In short, to match a literal backslash, one has to write '\\\\' as the RE string, because the regular expression must be "\\", and each backslash must be expressed as "\\" inside a regular Python string literal.

How do I print backslash in string?

Use the syntax "\\" within the string literal to represent a single backslash.

How do you backslash in C#?

\ is a special character (sign) In C#. It is used for escape sequences(break out) such as to print a new line – we use \n, to print a tab – we use \t. We have to use a double backslash (\\) to print a backslash (\). If we write \ within the message – it throws an error “Unrecognized escape sequence”.


2 Answers

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

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
Console.WriteLine(Path.Combine(path, "test"));

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

like image 191
Steve Avatar answered Sep 30 '22 16:09

Steve


You need escape it. \t is an escape-sequence for Tabs 0x09.

path + "\\test"

or use:

path + @"\test"

Better yet, let Path.Combine do the dirty work for you:

Path.Combine(path, "test");

Path resides in the System.IO namespace.

like image 21
Moo-Juice Avatar answered Sep 30 '22 16:09

Moo-Juice