Took me a while to find this bug in my code. Trying to create a temporary test directory:
Path.Combine("C:", "test");
Directory.CreateDirectory(path);
So this doesn't create the directory C:\test
. It seems to just create the directory test
in the local folder of the executing assembly.
This is because Path.Combine("C:", "test");
returns C:test
, and not C:\test
.
I don't pretend to know much about file systems so maybe the reason for this should be obvious, but I don't get it. I'm not sure why they implemented Path
that way, or why CreateDirectory
doesn't complain about an invalid directory name.
Well, you're combining a drive letter and a name. Under Windows that means "the name under the current directory of that drive". So for example:
C:\> cd foo
c:\foo> d:
d:\> mkdir c:bar
that would create c:\foo\bar
. So it seems consistent with the design of Windows (harking back to MS-DOS) to me - that isn't necessarily a sensible design for Windows, but it makes sense for .NET to be consistent with it.
Path.Combine
behaves this way, because :
is a valid VolumeSeparatorChar
- so a \
doesn't get appended to C:
.
From MSDN - Path.Combine Method (String, String):
If path1 is not a drive reference (that is, "C:" or "D:") and does not end with a valid separator character as defined in DirectorySeparatorChar, AltDirectorySeparatorChar, or VolumeSeparatorChar, DirectorySeparatorChar is appended to path1 before concatenation.
As for the behavior of CreateDirectory
- see the answer by Jon Skeet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With