Validate URL

Programming C#

Check if a given string contains a valid URL without the usage of messy RegEx expressions.

Of course you can include or exclude more Uri.Schemas as you like/need.
See the full list reference in the MSDN documetation.

 

using System;
using System.Text.RegularExpressions;

public class Program
{
public static void Main()
{
Console.WriteLine(IsValidUrl("http://www.wolfsys.net"));
Console.WriteLine(IsValidUrl("https://wolfsys.net"));
Console.WriteLine(IsValidUrl("https://www.wolfsys.net"));
Console.WriteLine(IsValidUrl("https://www.wolfsys"));
Console.WriteLine(IsValidUrl("//www.wolfsys.net"));
Console.WriteLine(IsValidUrl(".wolfsys.net"));
Console.WriteLine(IsValidUrl("wolfsys.net"));
Console.WriteLine(IsValidUrl("ftp://wolfsys.net/download/x.zip"));
}

public static bool IsValidUrl(string url)
{
Uri uri;
if (Uri.TryCreate(url, UriKind.Absolute, out uri) == false)
{
return false;
}
return uri.Scheme == Uri.UriSchemeHttp ||
uri.Scheme == Uri.UriSchemeHttps ||
uri.Scheme == Uri.UriSchemeFtp;
}
}