Wednesday, September 1, 2010

How to check URL is relative or absolute path

The relative path is a part of following format:

1)  ~/ or / : is the root site

ex: http://serverA/site1/site2/site3/default.aspx, with the current site is Site3, then ~/ will return http://serverA

2) ./: is the current site

3) ../: is the parent site

with above example will return http://serverA/Site1/Site2

The problem is how to check the input url whether using relative path or absolute path.

The simple code can be like this:

public bool IsRelative(string url)
    return (url == "~/" || url == "/" || url == "./" || url == "../");

But if you want to make sure the functioning work correctly, it should be:

public static bool IsUrlRelative(string url)
    Uri uri;
        uri = new Uri(url, UriKind.RelativeOrAbsolute);
        return false;
    return !uri.IsAbsoluteUri;

For now, SharePoint has supported the class to check this, it's very helpful:

SPUrlUtility supported some methods to work on URL:

public static string CombineUrl(string baseUrlPath, string additionalNodes);

return the concatenate 2 string

public static int IndexOfIllegalCharInUrlLeafName(string strLeafName);

return the position of illegal character in your string

public static bool IsLegalCharInUrl(char character);

indicate your character is legal or not

public static bool IsLegalFileName(string name);

indicate your file name is legal or not

public static bool IsProtocolAllowed(string fullOrRelativeUrl);

public static bool IsProtocolAllowed(string fullOrRelativeUrl, bool allowRelativeUrl);
public static bool IsUrlFull(string url);
public static bool IsUrlRelative(string url);

No comments: