为什么 Path.Combine 会产生相对路径的结果?
令我惊讶的是,这段代码没有产生预期的结果:
var basePath = @"\\server\BaseFolder";
var relativePath = @"\My\Relative\Folder";
var combinedPath = Path.Combine(basePath, relativePath);
结果是 \My\Relative\Folder
而不是预期的 \\server\BaseFolder\My\Relative\Folder
。
这是为什么呢?组合可能有或没有斜杠的相对路径的最佳方法是什么?
编辑:我知道我可以对relativePath进行字符串操作来检测并删除起始斜杠。有没有一种更安全的方法(我认为 Path.Combine 应该是安全的方法)来解释反斜杠和前斜杠?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将前导斜杠放在
relativePath
上,它应该可以工作。发生这种情况的原因是 Path.Combine 将
relativePath
解释为根(绝对)路径,因为在本例中,它以\
开头。您可以使用Path.IsRooted()
检查路径是相对路径还是根路径。来自文档:
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 usingPath.IsRooted()
.From the doc:
以斜杠开头的路径被解释为绝对路径而不是相对路径。如果您想保证
relativePath
将被视为相对路径,只需修剪掉斜杠即可。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.根据 此文档< /a>
Path.Combine
上的注释表明最好使用Path.Join()< /code>
对于用户可能已输入值的这种情况。看起来它是在 .NET Core 3.0 中引入的,
唯一的区别似乎是这种明确的场景,我们不想将我们组合的任何路径视为潜在的根路径。
According to this doc on
Path.Combine
the remark states it's best to usePath.Join()
for this scenario where the user may have entered values. Looks like it was introduced with .NET Core 3.0Seems like the only difference is this explicit scenario where we don't want to regard any of the paths we are combining as potential root paths.