Thread: ASP.NET/ResolveUrl in ASP.NET - The Perfect Solution

ResolveUrl in ASP.NET - The Perfect Solution

www.codeproject.com/KB/aspnet/resolveurl.aspx


public static string ResolveUrl(string relativeUrl)

{

    if (relativeUrl == null) throw new ArgumentNullException("relativeUrl");



    if (relativeUrl.Length == 0 || relativeUrl[0] == '/' || relativeUrl[0] == '\\')

        return relativeUrl;



    int idxOfScheme = relativeUrl.IndexOf(@"://", StringComparison.Ordinal);

    if (idxOfScheme != -1)

    {

        int idxOfQM = relativeUrl.IndexOf('?');

        if (idxOfQM == -1 || idxOfQM > idxOfScheme) return relativeUrl;

    }



    StringBuilder sbUrl = new StringBuilder();

    sbUrl.Append(HttpRuntime.AppDomainAppVirtualPath);

    if (sbUrl.Length == 0 || sbUrl[sbUrl.Length - 1] != '/') sbUrl.Append('/');



    // found question mark already? query string, do not touch!

    bool foundQM = false;

    bool foundSlash; // the latest char was a slash?

    if (relativeUrl.Length > 1

        && relativeUrl[0] == '~'

        && (relativeUrl[1] == '/' || relativeUrl[1] == '\\'))

    {

        relativeUrl = relativeUrl.Substring(2);

        foundSlash = true;

    }

    else foundSlash = false;

    foreach (char c in relativeUrl)

    {

        if (!foundQM)

        {

            if (c == '?') foundQM = true;

            else

            {

                if (c == '/' || c == '\\')

                {

                    if (foundSlash) continue;

                    else

                    {

                        sbUrl.Append('/');

                        foundSlash = true;

                        continue;

                    }

                }

                else if (foundSlash) foundSlash = false;

            }

        }

        sbUrl.Append(c);

    }



    return sbUrl.ToString();

}