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

前端 未结 10 972
栀梦
栀梦 2020-12-13 12:08

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 applicatio

10条回答
  •  情歌与酒
    2020-12-13 12:34

    I wanted to check if the url also contains a domain extension, it needs to be a valid website url.

    This is what i came up with:

     public static bool IsValidUrl(string url)
            {
                if (string.IsNullOrEmpty(url)) { return false;}
    
                if (!url.StartsWith("http://"))
                {
                    url = "http://" + url;    
                }
    
                Uri outWebsite;
    
                return Uri.TryCreate(url, UriKind.Absolute, out outWebsite) && outWebsite.Host.Replace("www.", "").Split('.').Count() > 1 && outWebsite.HostNameType == UriHostNameType.Dns && outWebsite.Host.Length > outWebsite.Host.LastIndexOf(".") + 1 && 255 >= url.Length;
            }
    

    I've tested the code with linqpad:

        void Main()
    {
            // Errors
            IsValidUrl("www.google/cookie.png").Dump();
            IsValidUrl("1234").Dump();
            IsValidUrl("abcdef").Dump();
            IsValidUrl("abcdef/test.png").Dump();
            IsValidUrl("www.org").Dump();
            IsValidUrl("google").Dump();
            IsValidUrl("google.").Dump();
            IsValidUrl("google/test").Dump();
            IsValidUrl("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0").Dump();
            IsValidUrl("").Dump();
            IsValidUrl("Accept: application/json, text/javascript, */*; q=0.01").Dump();
            IsValidUrl("DNT: 1").Dump();
    
            Environment.NewLine.Dump();
    
            // Success
            IsValidUrl("google.nl").Dump();
            IsValidUrl("www.google.nl").Dump();
            IsValidUrl("http://google.nl").Dump();
            IsValidUrl("http://www.google.nl").Dump();
    }
    

    Results:

    False False False False False False False False False False False False

    True True True True

提交回复
热议问题