I have to check whether an image is jpg or png (or none of them) and return the format. I have an "ID" of a picture, which I have to look up online and guess the format.
I have two cases:
mydomain.com/ID.jpg
mydomain.com/ID.png
If none work, then return "error" or "unknown type", otherwise return the type of the image.
I tried various methods, but I can't get it working, for some reason I get exceptions.
First, I tried this, but I was getting web exception.
using (WebClient wc = new WebClient())
{
try
{
if (wc.DownloadString(mydomain.com/ID.png).Contains("PNG"))
{
wc.DownloadFile(url, filepath);
}
else
{
wc.DownloadFile(url, filepath);
}
}
catch (WebException ex)
{
if (ex.Response != null && ex.Status == WebExceptionStatus.ProtocolError)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.Forbidden || resp.StatusCode == HttpStatusCode.NotFound)
{
continue;
}
}
throw;
}
}
Then I tried a function to check if an URL is an image, and call it
bool IsImageUrl(string URL)
{
var req = (HttpWebRequest)HttpWebRequest.Create(URL);
req.Method = "HEAD";
using (var resp = req.GetResponse())
{
return resp.ContentType.ToLower(CultureInfo.InvariantCulture)
.StartsWith("image/");
}
}
Calling it like this:
try
{
if (IsImageUrl("mydomain.com/ID.jpg"))
{
MessageBox.Show("jpg");
}
else
{
MessageBox.Show("png");
}
}
catch (Exception ex)
{
MessageBox.Show("other format or error");
}
I also tried this:
try
{
HttpWebRequest request = HttpWebRequest.Create("mydomain.com/ID.jpg") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string contentType = "";
if (response != null)
contentType = response.ContentType;
MessageBox.Show(contentType);
}
catch (WebException ex)
{
if (ex.Response != null && ex.Status == WebExceptionStatus.ProtocolError)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.Forbidden || resp.StatusCode == HttpStatusCode.NotFound)
{
//continue;
}
}
throw;
}
But I still have the same problem, it throws an exception instead of return it..
So, my question is: Given the situation in the beginning of post, I need to check two URLs, by adding .jpg and .png at the end of each, whether one of them is valid, if so, return which (the format), otherwise return "unknown format".