Path.Combine() behaviour with drive letters

2020-08-09 10:11发布

问题:

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?

回答1:

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.



回答2:

The path c: and c:\ are no 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: + \



标签: c#