在C#中,如何检查路径是否为虚拟路径?

Dan*_* T. 16 c# asp.net file path

可能的虚拟路径:

/folder1/folder2/image.jpg
~/folder1/folder2/image.jpg
folder1/folder2/image.jpg
Run Code Online (Sandbox Code Playgroud)

具体路径:

C:\folder1\folder2\image.jpg
D:\folder1\folder2\image.jpg
C:/folder1/folder2/image.jpg
C:/folder1\folder2/image.jpg
Run Code Online (Sandbox Code Playgroud)

如何以不容易失败的方式检查路径是否为虚拟路径?我问的原因是因为当我Server.MapPath()在具体路径上使用它时会抛出异常.但是,我传递的内容Server.MapPath()可以是我上面提供的任何一个示例,我不知道它在运行时之前是什么.

Kev*_*son 18

这对我来说效果很好:

protected string GetPath(string path)
{
    if (Path.IsPathRooted(path))
    {
        return path;
    }

    return Server.MapPath(path);
}
Run Code Online (Sandbox Code Playgroud)

  • 这对于`/ folder1/folder2/image.jpg`不起作用,它将返回`true` (3认同)

Sim*_*ell 8

Path.GetFullPath(string path)满足您的需求?您可以使用该方法然后比较路径是否更改.

if (path == Path.GetFullPath(path))
{
    // This is the full path (no changes)
}
else
{
    // This is not the full path i.e. 'virtual' (changes)
}
Run Code Online (Sandbox Code Playgroud)

参考: http ://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx