Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is System.IO implemented this way

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.

like image 731
fearofawhackplanet Avatar asked Nov 30 '22 07:11

fearofawhackplanet


2 Answers

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.

like image 124
Jon Skeet Avatar answered Dec 04 '22 11:12

Jon Skeet


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.

like image 44
Oded Avatar answered Dec 04 '22 09:12

Oded