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

前端 未结 10 969
栀梦
栀梦 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:52

    Or this source code good image valid optimization:

     public static string ValidateImage(string absoluteUrl,string defaultUrl)
            { 
               Uri myUri=null; 
               if (Uri.TryCreate(absoluteUrl, UriKind.Absolute, out myUri))
                {
                    using (WebClient client = new WebClient())
                    {
                        try
                        {
                            using (Stream stream = client.OpenRead(myUri))
                            {
                                Image image = Image.FromStream(stream);
                                return (image != null) ? absoluteUrl : defaultUrl;
                            }
                        }
                        catch (ArgumentException)
                        {
                            return defaultUrl;
                        }
                        catch (WebException)
                        {
                            return defaultUrl;
                        }
                    }
                }
                else
                {
                    return defaultUrl;
                }
            }
    

    Sou and demo asp.net mvc source image created:

    
    

提交回复
热议问题