Why Path.Combine doesn't add the Path.DirectorySeparatorChar after the drive designator?
Asked Answered
P

2

19
var actual = Path.Combine("c:", "filename");
var expected = @"c:\filename";
Assert.AreEqual(expected, actual);

Result

{Assert.AreEqual failed. Expected:<c:\filename>. Actual:<c:filename>.

Why?

Poetaster answered 6/10, 2009 at 20:28 Comment(0)
M
27

C:filename is a valid path and is different from C:\filename. C:filename is the file filename in the current directory on the C: drive whereas C:\filename is the file filename in the root of that drive. Apparently they wanted to keep the functionality of refering to the current directory on some drive.

This behaviour is described here in MSDN

Moo answered 6/10, 2009 at 20:36 Comment(3)
This is a hold-over from DOS 1.x IIRC... :-)Botryoidal
Freaky... this is unintuitive. What is the way to get the expected value ? Path.Combine( drive + @"\", path ) ?Chau
@Chau - It's only unintuitive because the way paths work in the Windows OS is not as simple as one might think. See the MSDN article I linked to to find a description of how Windows paths work. Path.Combine() combines two paths. I would not use string concatenation in the way you suggest because that defeats the whole purpose of Path.Combine(). AFAIC you should be careful in the way you specify your paths. If you mean "C:\" use that, if OTOH you mean "C:" (which is different but just as valid) then use that.Moo
D
5

MSDN doesn't seem to explain why, but does provide documentation on what you're seeing:

Path.Combine(string path1, string path2)

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.

Disoperation answered 6/10, 2009 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.