Skip to main content

Indicates whether the string is well-formed, and is not required to be further escaped.

using System.Web;

namespace Helpers
{
    public static class UrlHelper
    {
        /// <summary>
        /// Indicates whether the string used to construct this
        /// Uri is well-formed and is not required to be further escaped.
        /// </summary>
        /// <param name="uriString">The URI string.</param>
        /// <param name="uriKind">Kind of the URI.</param>
        /// <returns></returns>
        public static bool IsWellFormedUriString(string uriString, UriKind uriKind = UriKind.Absolute)
        {
            if (string.IsNullOrWhiteSpace(uriString))
            {
                return false;
            }

            Uri uri;
            return Uri.TryCreate(uriString, uriKind, out uri) && uri.IsWellFormedOriginalString();
        }
    }
}

//
// Option 2 (simplified)
//

string url = "https://www.google.com";
if (System.Uri.IsWellFormedUriString(url, System.UriKind.Absolute))
{
    Console.WriteLine("'{0}' is valid.", url);
}