Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Path.Combine produce this result with a relative path?

To my surprise, this code does not produce expected results:

var basePath = @"\\server\BaseFolder";
var relativePath = @"\My\Relative\Folder";

var combinedPath = Path.Combine(basePath, relativePath);

The result is \My\Relative\Folder instead of the expected \\server\BaseFolder\My\Relative\Folder.

Why is this? What's the best way to combine relative paths that may or may not have a slash in them?

EDIT: I'm aware that I can just do string manipulation on relativePath to detect and remove a starting slash. Is there a safer way of doing this (I thought Path.Combine was supposed to be the safe way) that will account for backslashes and frontslashes?

like image 441
Brandon Avatar asked Apr 21 '11 18:04

Brandon


2 Answers

Drop the leading slash on relativePath and it should work.

The reason why this happens is that Path.Combine is interpreting relativePath as a rooted (absolute) path because, in this case, it begins with a \. You can check if a path is relative or rooted by using Path.IsRooted().

From the doc:

If the one of the subsequent paths is an absolute path, then the combine operation resets starting with that absolute path, discarding all previous combined paths.

like image 60
Jason Punyon Avatar answered Sep 28 '22 03:09

Jason Punyon


Paths that start with a slash are interpreted as being absolute rather than relative. Simply trim the slash off if you want to guarantee that relativePath will be treated as relative.

var basePath = @"\\server\BaseFolder";
var relativePath = @"\My\Relative\Folder";

var combinedPath = Path.Combine(basePath, relativePath.TrimStart('/', '\\'));
like image 40
Greg Avatar answered Sep 28 '22 02:09

Greg