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

后端 未结 2 990
余生分开走
余生分开走 2020-12-06 04:02

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

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

var         


        
相关标签:
2条回答
  • 2020-12-06 04:22

    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.

    0 讨论(0)
  • 2020-12-06 04:47

    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('/', '\\'));
    
    0 讨论(0)
提交回复
热议问题