Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path.Combine() behaviour with drive letters

Tags:

c#

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?

like image 663
Petaflop Avatar asked Jan 22 '18 13:01

Petaflop


3 Answers

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.

like image 82
Kevin Gosse Avatar answered Oct 19 '22 19:10

Kevin Gosse


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 to path1 before concatenation.

So your first path, which is the drive letter, does not get a directory separator appended.

like image 35
CodeCaster Avatar answered Oct 19 '22 19:10

CodeCaster


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: + \

like image 31
John Alexiou Avatar answered Oct 19 '22 19:10

John Alexiou