为什么 Path.Combine 用相对路径产生这个结果? [英] Why does Path.Combine produce this result with a relative path?

查看:38
本文介绍了为什么 Path.Combine 用相对路径产生这个结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令我惊讶的是,这段代码没有产生预期的结果:

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

var basePath = @"\serverBaseFolder";
var relativePath = @"MyRelativeFolder";

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

结果是 MyRelativeFolder 而不是预期的 \serverBaseFolderMyRelativeFolder.

The result is MyRelativeFolder instead of the expected \serverBaseFolderMyRelativeFolder.

这是为什么?组合可能包含或不包含斜杠的相对路径的最佳方法是什么?

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

我知道我可以对 relativePath 进行字符串操作来检测和删除起始斜杠.有没有更安全的方法(我认为 Path.Combine 应该是安全的方法)来解决反斜杠和前斜杠?

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?

推荐答案

relativePath 上删除前导斜杠,它应该可以工作.

Drop the leading slash on relativePath and it should work.

发生这种情况的原因是 Path.Combine 将 relativePath 解释为根(绝对)路径,因为在这种情况下,它以 开头.您可以使用 Path.IsRooted() 来检查路径是相对路径还是根路径.

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().

来自文档:

如果后续路径之一是一个绝对路径,然后组合操作重置从那开始绝对路径,丢弃所有以前的组合路径.

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.

这篇关于为什么 Path.Combine 用相对路径产生这个结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆