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

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

问题描述

要我吃惊的是,这个code不会产生预期的结果:

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);

结果是 \我\相对\文件夹而不是预期的 \\服务器\ BaseFolder \我\相对\文件夹

这是为什么?什么是结合相对路径,可能会或可能不会有在其中一个斜线最好的方法是什么?

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 被认为是安全的方式),将占到反斜线和frontslashes?

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为帧间preting 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().

DOC

如果随后的路径的一个是   绝对路径,则结合   开始该操作重置   绝对路径,丢弃所有的previous   结合路径。

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天全站免登陆