Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DirectoryExists("c:temp\\foo") returns true when directory doesn't exist!

Tags:

c#

.net

file-io

OK, I got bit by something that seems a tad weird. I realize it was my mistake to not format the pathname correctly, but I would expect the following test to return false, especially since the folder did not exist.

DirectoryExists("C:temp\\foo")

but in fact, it returns true even though the directory does not exist!

The code should be

DirectoryExists("C:\\temp\\foo")

Can someone explain to me why I get a false positive from the first version? I would expect it to return false or throw an exception perhaps, but not return true.

like image 859
Dan Bailiff Avatar asked Nov 16 '10 19:11

Dan Bailiff


1 Answers

This API is behaving properly but often appears incorrect the first time you encounter this behavior. Omitting the \ after the volume letter has special semantics. It will replace the volume specifier with value passed into the last call to SetCurrentDirectory for that volume. How this is remembered is discussed here

  • http://msdn.microsoft.com/en-us/library/aa363806(v=VS.85).aspx

In this case the last value passed in was either c:\ or the current directory simply hadn't been set. Hence the call actually became the second version

Directory.Exists("c:\\temp\\foo")

This correctly evaluated to true

Why this happens for Directory.Exists is that deep, deep down in the function it uses GetFullPathName which relies on this behavior (see the linked documentation).

like image 134
JaredPar Avatar answered Oct 08 '22 08:10

JaredPar