1

我想检查给定路径是否是明确指定特定位置的显式路径。所以,我想排除如下路径:

file
directory
directory\file
C:file
\directory\file

我想允许:

C:\file
C:\directory
C:\directory\file
\\server\share\file
\\server\share\directory\file

Path.IsRooted方法几乎可以满足我的需要,但是对于上面的最后两个示例(C:file\directory\file),它返回 true,它们分别表示当前目录和当前驱动器。

我可以使用另一种方法吗?请注意,我不在乎文件/目录是否实际存在。

4

2 回答 2

2

使用Path.GetFullPath()并将结果与​​原始字符串进行比较:

bool IsPathAbsolute(string path)
{
    return Path.GetFullPath(path) == path;
}
于 2012-12-05T15:16:21.360 回答
1

深入研究源代码可以发现实际实现Path.IsPathRooted是这样的:

public static bool IsPathRooted(string path)
{
    if (path != null)
    {
        Path.CheckInvalidPathChars(path);
        int length = path.Length;
        if ((length >= 1 && (path[0] == Path.DirectorySeparatorChar || path[0] == Path.AltDirectorySeparatorChar))
            || (length >= 2 && path[1] == Path.VolumeSeparatorChar))
        {
            return true;
        }
    }
    return false;
}

Now it becomes evident how to adjust it to suit your needs - you can define a new method and slightly change the conditions (and maybe refactor them a little - they do not look very good):

if ((length >= 1 && ((path[0] == Path.DirectorySeparatorChar && path[1] == Path.DirectorySeparatorChar) || path[0] == Path.AltDirectorySeparatorChar))
    || (length >= 3 && path[1] == Path.VolumeSeparatorChar && path[2] == Path.DirectorySeparatorChar))
于 2012-12-05T15:27:19.030 回答