Brody Schuman
Brody Schuman

Reputation: 43

ASP.Net C# - Check if WebClient() connection returns 404 or access denied

I just have a quick question about checking for what WebClient() returns. I want to see if the URL returns a 404 error or an access denied error. How could I implement that in my current code?

Here is what my code looks like right now:

public static Tuple<string, string> DownloadImageFromURL(string URL)
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            byte[] imageData = new WebClient().DownloadData(URL);
            MemoryStream imgStream = new MemoryStream(imageData);
            Image img = Image.FromStream(imgStream);

            string imageWidth = img.Width.ToString();
            string imageHeight = img.Height.ToString();
           

            return new Tuple<string, string>(imageWidth, imageHeight);
        }

Thank you for any help, greatly appreciated!

Upvotes: 1

Views: 130

Answers (1)

Brody Schuman
Brody Schuman

Reputation: 43

Okay, already figured it out. Here is what I did for future reference:

public static Tuple<string, string> DownloadImageFromURL(string URL)
        {
            string imageWidth = "";
            string imageHeight = "";
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            using( var client = new WebClient())
            {
                try
                {
                    
                    byte[] imageData = client.DownloadData(URL);
                    MemoryStream imgStream = new MemoryStream(imageData);
                    Image img = Image.FromStream(imgStream);

                    imageWidth = img.Width.ToString();
                    imageHeight = img.Height.ToString();
                }
                catch (WebException wex)
                {
                    if(wex.Response is HttpWebResponse)
                    {
                        HttpWebResponse response = (HttpWebResponse)wex.Response;
                        System.Diagnostics.Debug.WriteLine("IMAGE: Error code: " + response.StatusCode);
                    }
                }
            }
            
            return new Tuple<string, string>(imageWidth, imageHeight);
        }

Upvotes: 1

Related Questions