Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how do you check if a path is virtual or not?

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.

like image 542
Daniel T. Avatar asked Oct 13 '10 03:10

Daniel T.


People also ask

What is '~' in C language?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What does the || mean in C?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.

What is & operator in C?

&& This is the AND operator in C programming language. It performs logical conjunction of two expressions. ( If both expressions evaluate to True, then the result is True.


2 Answers

This works well enough for me:

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

    return Server.MapPath(path);
}
like image 175
Kevin Wilson Avatar answered Oct 30 '22 18:10

Kevin Wilson


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

like image 29
Simon Campbell Avatar answered Oct 30 '22 16:10

Simon Campbell