-->

c# why when the path is “C:” the directoryInfo tak

2020-03-22 07:38发布

问题:

Why when i give the path "c:" it changed me directly to application folder?

    static void Main(string[] args)
    {
        DirectoryInfo dir = new DirectoryInfo("c:");
        Console.WriteLine(dir.FullName);
        Console.ReadLine();
    }

The output is the following:

c:\users...\documents\visual studio 2010\projects\consoleApplication9\bin\debug

But when I give @"c:\" it goes to disk c: despite that "d:" and @"d:\" takes to disk d:.

So I need a way to let "c:" takes to disk c:

Thanks in advance!

回答1:

static void Main(string[] args) 
    { 
        string YourDir = "c:";

        if (!YourDir.Substring(YourDir.Length - 1, 1).Equals(@"\"))
            YourDir += @"\";
        DirectoryInfo dir = new DirectoryInfo(YourDir); 
        Console.WriteLine(dir.FullName); 
        Console.ReadLine(); 
    } 


回答2:

Just "c:" means "the current directory on the C drive" whereas @"c:\" means "root of the C drive". This works the same way from a command prompt...



回答3:

C: is just the volume specifier, so it will change to your current path on that volume, which would be the working path of the application.

D: takes you to root simply because your current folder for that volume happens to be at root.



回答4:

Use the following

  static void Main(string[] args)
  {          
      DirectoryInfo dir = new DirectoryInfo(@"c:\");
      Console.WriteLine(dir.FullName);
      Console.ReadLine();
  }       

The Base Directory at the time when you do c: the application doesn't understand that so it returns the Directory of where the application was launched / run from.

Notice that dir = {.} if you would have passed in a literal directory path you would have gotten the expected results..