3

I had a bizarre situation when try to access the sub directories of my c: drive:

first I tried the following code, the output was 0 (zero):

MessageBox.Show(new DirectoryInfo("c:").GetDirectories().Length.ToString());

but when add '\' to path (c:), it showed the exact number of sub folders in c: drive.

MessageBox.Show(new DirectoryInfo("c:\\").GetDirectories().Length.ToString());

but tried a another drive (d:) like:

MessageBox.Show(new DirectoryInfo("d:").GetDirectories().Length.ToString());

it retrieves all the sub direcotories.

can anyone explain why is that happened?


Well thanks guys. Now I got the point just "c:" returns current directory not root "c:\". But I don't get any errors as bemused mentioned.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
faz
  • 31
  • 1

2 Answers2

5

\ is an escape character.
\" inserts a " character in a string, without terminating the string literal (eg, "I have a \"quoted\" word!")

Use a literal string: @"C:\"; these literals ignore escape characters.


The path C: without a \ refers to the current directory within the C drive, which is not necessarily C:\ (each drive has its own current directory).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
5

My guess is that it is interpreting "c:" as the current environment folder on the c: drive, which has no subfolders. But when you specify a different drive than the one it's executing on ("d:"), it defaults to the root of that drive.

It should be easy enough check - compare the full path of DirectoryInfo("c:") and DirectoryInfo("c:\")

Console.WriteLine(new System.IO.DirectoryInfo(@"c:").FullName);

>> c:\project\test\bin\debug

Console.WriteLine(new System.IO.DirectoryInfo(@"c:\").FullName);

>> c:\
Jason
  • 86,222
  • 15
  • 131
  • 146