A better way to validate URL in C# than try-catch?

Viewed 54620

I'm building an application to retrieve an image from internet. Even though it works fine, it is slow (on wrong given URL) when using try-catch statements in the application.

(1) Is this the best way to verify URL and handle wrong input - or should I use Regex (or some other method) instead?

(2) Why does the application try to find images locally if I don't specify http:// in the textBox?

private void btnGetImage_Click(object sender, EventArgs e)
{
    String url = tbxImageURL.Text;
    byte[] imageData = new byte[1];

    using (WebClient client = new WebClient())
    {
        try
        {
            imageData = client.DownloadData(url);
            using (MemoryStream ms = new MemoryStream(imageData))
            {
                try
                {
                    Image image = Image.FromStream(ms);
                    pbxUrlImage.Image = image;
                }
                catch (ArgumentException)
                {
                    MessageBox.Show("Specified image URL had no match", 
                        "Image Not Found", MessageBoxButtons.OK, 
                        MessageBoxIcon.Error);
                }
            }
        }
        catch (ArgumentException)
        {
            MessageBox.Show("Image URL can not be an empty string", 
                "Empty Field", MessageBoxButtons.OK, 
                MessageBoxIcon.Information);
        }
        catch (WebException)
        {
            MessageBox.Show("Image URL is invalid.\nStart with http:// " +
                "and end with\na proper image extension", "Not a valid URL",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    } // end of outer using statement
} // end of btnGetImage_Click

EDIT: I tried the suggested solution by Panagiotis Kanavos (thank you for your effort!), but it only gets caught in the if-else statement if the user enters http:// and nothing more. Changing to UriKind.Absolute catches empty strings as well! Getting closer :) The code as of now:

private void btnGetImage_Click(object sender, EventArgs e)
{
    String url = tbxImageURL.Text;
    byte[] imageData = new byte[1];
    Uri myUri;

    // changed to UriKind.Absolute to catch empty string
    if (Uri.TryCreate(url, UriKind.Absolute, out myUri))
    {
        using (WebClient client = new WebClient())
        {
            try
            {
                imageData = client.DownloadData(myUri);
                using (MemoryStream ms = new MemoryStream(imageData))
                {
                    imageData = client.DownloadData(myUri);
                    Image image = Image.FromStream(ms);
                    pbxUrlImage.Image = image;
                }
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Specified image URL had no match",
                    "Image Not Found", MessageBoxButtons.OK, 
                    MessageBoxIcon.Error);
            }
            catch (WebException)
            {
                MessageBox.Show("Image URL is invalid.\nStart with http:// " +
                    "and end with\na proper image extension", 
                    "Not a valid URL",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
    else
    {
        MessageBox.Show("The Image Uri is invalid.\nStart with http:// " +
            "and end with\na proper image extension", "Uri was not created",
            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

I must be doing something wrong here. :(

10 Answers

you can use the function Uri.TryCreate As Panagiotis Kanavos suggested if you like to test and create a url or you can use Uri.IsWellFormedUriString function as suggested by Todd Menier if you just wanted to test the validity of Url. this can by handy if you are just validating user input for now and need to create url some time later in life time of your application.

**But my post is for the People, like myself :( , still hitting their heads against .net 1.1 **

both above methods were introduced in .net 2.0 so you guys still have to use try catch method, which, in my opinion, is still far better than using regular expression.

private bool IsValidHTTPURL(string url)
{
    bool result = false;

    try
    {
        Uri uri = new Uri(url);

        result = (uri.Scheme == "http" || uri.Scheme == "https");
    }
    catch (Exception ex) 
    { 
        log.Error("Exception while validating url", ex); 
    }

    return result;
}

I ran into a very similar case so I wrote a static class which can be easily used along with xUnit tests to verify the logic passed several cases.

Usage (returns ValidationModel):

var message = UrlValidator.Validate(input).ValidationMessage;

or

var result = UrlValidator.Validate(input).IsValid;

ValidationModel.cs

    public class ValidationModel
    {
        public const string InvalidScheme = "Invalid URI scheme.";
        public const string EmptyInputValue = "Empty input value.";
        public const string InvalidUriFormat = "Invalid URI format.";
        public const string PassedValidation = "Passed validation";
        public const string HttpScheme = "http://";
        public const string HttpsScheme = "https://";

        public bool IsValid { get; set; }
        public string ValidationMessage { get; set; }
        
    }

UrlValidator.cs

    public static class UrlValidator
    {
        public static ValidationModel Validate(string input)
        {
            var validation = new ValidationModel();

            if (input == string.Empty)
            {
                validation.IsValid = false;
                validation.ValidationMessage = ValidationModel.EmptyInputValue;
                return validation;
            }

            try
            {
                var uri = new Uri(input);
                var leftPart = uri.GetLeftPart(UriPartial.Scheme);

                if (leftPart.Equals(ValidationModel.HttpScheme) || leftPart.Equals(ValidationModel.HttpsScheme))
                {
                    validation.IsValid = true;
                    validation.ValidationMessage = ValidationModel.PassedValidation;
                    return validation;
                }
                
                validation.IsValid = false;
                validation.ValidationMessage = ValidationModel.InvalidScheme;
            }
            catch (UriFormatException)
            {
                validation.IsValid = false;
                validation.ValidationMessage = ValidationModel.InvalidUriFormat;
            }
            
            return validation;
        }
    }

UrlValidatorTests.cs

    public class UrlValidatorTests
    {
        [Theory]
        [InlineData("http://intel.com", true, ValidationModel.PassedValidation)]
        [InlineData("https://intel.com", true, ValidationModel.PassedValidation)]
        [InlineData("https://intel.com/index.html", true, ValidationModel.PassedValidation)]
        [InlineData("", false, ValidationModel.EmptyInputValue)]
        [InlineData("http://", false, ValidationModel.InvalidUriFormat)]
        [InlineData("//intel.com", false, ValidationModel.InvalidScheme)]
        [InlineData("://intel.com", false, ValidationModel.InvalidUriFormat)]
        [InlineData("f://intel.com", false, ValidationModel.InvalidScheme)]
        [InlineData("htttp://intel.com", false, ValidationModel.InvalidScheme)]
        [InlineData("intel.com", false, ValidationModel.InvalidUriFormat)]
        [InlineData("ftp://intel.com", false, ValidationModel.InvalidScheme)]
        [InlineData("http:intel.com", false, ValidationModel.InvalidUriFormat)]
        public void Validate_Input_ExpectedResult(string input, bool expectedResult, string expectedInvalidMessage)
        {
            //Act
            var result = UrlValidator.Validate(input);

            //Assert
            Assert.Equal(expectedResult, result.IsValid);
            Assert.Equal(expectedInvalidMessage, result.ValidationMessage);
        }
    }

TEST RESULTS:

test results

Related