According to the official documentation regarding Path.Combine
method: https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx
Remarks
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.
This means that it will not add the \
after the drive letter, so this piece of code:
var path1 = @"c:";
var path2 = @"file.txt";
Path.Combine(path1, path2);
will produce C:file.txt
which doesn't forcely point to a file file.txt
placed in c:
.
What's the reason behind this?
Path.Combine
works that way because c:file.txt
is actually a valid path.
According to Microsoft documentation on NTFS paths:
If a file name begins with only a disk designator but not the backslash after the colon, it is interpreted as a relative path to the current directory on the drive with the specified letter. Note that the current directory may or may not be the root directory depending on what it was set to during the most recent "change directory" operation on that disk.
In a nutshell, c:file.txt
will search the file in the current directory of the C: drive, while c:\file.txt
will search the file at the root folder of the drive (ignoring the current directory).
Since Path.Combine
has no way to know what was the behavior you expected, it cannot automatically add backslashes.
It's in the documentation:
If
path1
is not a drive reference (that is, "C:" or "D:") and does not end with a valid separator character [..],DirectorySeparatorChar
is appended topath1
before concatenation.
So your first path, which is the drive letter, does not get a directory separator appended.
The path c:
and c:\
are not the same.
c:
is a drive specification, and the OS appends the current folder when needed.
c:\
is the root folder of a drive, as in c:
+ \
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