views:

89

answers:

3

Possible virtual paths:

/folder1/folder2/image.jpg
~/folder1/folder2/image.jpg
folder1/folder2/image.jpg

Concrete path:

C:\folder1\folder2\image.jpg
D:\folder1\folder2\image.jpg
C:/folder1/folder2/image.jpg
C:/folder1\folder2/image.jpg

How do you check whether a path is virtual or not in a way that's not prone to failure? The reason why I'm asking is because when I use Server.MapPath() on a concrete path, it will throw an exception. However, what I'm passing to Server.MapPath() can be any one of the examples I provided above and I don't know what it is before run-time.

+1  A: 

I would use Reflector to check what Server.MapPath() does and do that. :)

An alternative might be System.IO.Path.GetPathRoot() - if it returns null then it's a relative path. This is a little bit of a hack, though, since it doesn't know anything about web paths, so if it's works it would work by coincidence.

Evgeny
A: 

See if Path.IsPathRooted help.

        //
    // Summary:
    //     Gets a value indicating whether the specified path string contains absolute
    //     or relative path information.
    //
    // Parameters:
    //   path:
    //     The path to test.
    //
    // Returns:
    //     true if path contains an absolute path; otherwise, false.
    //
    // Exceptions:
    //   System.ArgumentException:
    //     path contains one or more of the invalid characters defined in System.IO.Path.GetInvalidPathChars().
    public static bool IsPathRooted(string path);
saurabh
That does seem like the obvious choice, but it would return `true` for "/folder1/folder2/image.jpg". (I've fallen into this trap myself, so I'm not downvoting you!)
Evgeny
A: 

Would Path.GetFullPath(string path) fit your needs? You could use that method then compare if the path changed.

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

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

Simon Campbell