views:

261

answers:

2
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?

+3  A: 

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.

Gavin Miller
+1 for the edit =)
Jader Dias
+13  A: 

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

Peter van der Heijden
This is a hold-over from DOS 1.x IIRC... :-)
Christian Hayter
Freaky... this is unintuitive. What is the way to get the expected value ? `Path.Combine( drive + @"\", path )` ?
Gishu
@Gishu - 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.
Peter van der Heijden