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?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

2 Answers2

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

heijp06
  • 11,558
  • 1
  • 40
  • 60
  • 4
    This is a hold-over from DOS 1.x IIRC... :-) – Christian Hayter Oct 06 '09 at 20:38
  • 3
    Freaky... this is unintuitive. What is the way to get the expected value ? `Path.Combine( drive + @"\", path )` ? – Gishu Apr 28 '10 at 07:25
  • 2
    @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. – heijp06 Apr 28 '10 at 08:22
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.

Community
  • 1
  • 1
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188