Vahan
Vahan

Reputation: 3288

How can I know from the URL if it is the correct image URL or not in C#?

I have an array of images URLs. I want to know which of these URLs are correct and which not, without using try-catch, and I want to do that as fast as possible.

Upvotes: 0

Views: 182

Answers (1)

Maple
Maple

Reputation: 350

I would think the only way for you to know which urls are correct is to just make an HTTP request to the URL. If you have a lot of pictures, this will always take time. You can minimize that time by just making a HEAD HTTP request (as opposed to a GET and downloading the whole response), and checking the status code of the response. If the status code is 200, you might assume that you get the picture you're looking for, if it is 404, you know the url is incorrect.

Code might be something like:

HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://example.com/");
req.Method = "HEAD";
HttpWebResponse resp = (HttpWebResponse)(req.GetResponse());
HttpStatusCode statuscode = resp.StatusCode;

A note on getting a 200 response: If you get a 200 repsonse, you cannot be sure that you are actually getting image you want. You might be getting something else, e.g. a redirect from the image url.

Upvotes: 1

Related Questions