How to check whether a string is a valid HTTP URL?

Louis Rhys picture Louis Rhys · Sep 28, 2011 · Viewed 202.9k times · Source

There are the Uri.IsWellFormedUriString and Uri.TryCreate methods, but they seem to return true for file paths etc.

How do I check whether a string is a valid (not necessarily active) HTTP URL for input validation purposes?

Answer

Arabela Paslaru picture Arabela Paslaru · Sep 28, 2011

Try this to validate HTTP URLs (uriName is the URI you want to test):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && uriResult.Scheme == Uri.UriSchemeHttp;

Or, if you want to accept both HTTP and HTTPS URLs as valid (per J0e3gan's comment):

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) 
    && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);