tsJensen

A quest for software excellence...

Url Utils Helper Class May Be Helpful

Sometimes the odd helper class is useful. This one might even be a decent candidate for some .NET 3.5 extension methods. These URL utilities are quite self explanatory and by no means are a complete set of URL helper methods that would be useful, but who knows, they might have something you're looking for.

using System;
using System.Collections.Generic;
using System.Text;

namespace HelperCode
{
    internal static class UrlUtils
    {
        internal static string GetTldFromUrl(string url)
        {
            string tld = UrlUtils.GetHostFromUrl(url);
            if (tld != null && tld.Contains('.'))
            {
                string[] parts = tld.Split('.');
                if (parts.Length > 0)
                {
                    tld = parts[parts.Length - 1];
                }
            }
            return tld;
        }

        internal static string GetHostFromUrl(string url)
        {
            string retval = null;
            try
            {
                Uri uri = new Uri(url);
                retval = uri.Host.ToLower();
            }
            catch
            {
                retval = null;
            }
            return retval;
        }

        internal static string GetSchemeFromUrl(string url)
        {
            string retval = null;
            try
            {
                Uri uri = new Uri(url);
                retval = uri.Scheme.ToLower();
            }
            catch
            {
                retval = null;
            }
            return retval;
        }
    }
}

If you have a better way to do it, please, by all means, let us know. There are no doubt better ways. :)