14

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.

misha312
  • 1,443
  • 4
  • 18
  • 27

6 Answers6

32

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

Steve
  • 213,761
  • 22
  • 232
  • 286
20

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.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
8

There are two options:

  1. Use the @ symbol e.g.: path + @"\test"
  2. use a double backslash e.g.: path + "\\test"
Greg Dietsche
  • 862
  • 8
  • 16
6

string add;

add += "\\"; //or :"\\" means backslash
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
3

Backslash '\' is an escape character for strings in C#. You can:

  • use Path.Combine

    Path.Combine(path, "test");
    
  • escape the escape character.

    Console.WriteLine(path+"\\test");
    
  • use the verbatim string literal.

    Console.WriteLine(path + @"\test");
    
jszigeti
  • 373
  • 4
  • 11
tafa
  • 7,146
  • 3
  • 36
  • 40
1

the backslash is an escape character, so use
Console.WriteLine(path+"\\test");
or
Console.WriteLine(path+@"\test");