Codesnipp.it Social Code Sharing

Trey Copeland

Check to see if remote image exists using C#

by Trey Copeland on Jan 21, 2011

public void BuildImg() { // The two different images as strings. string url1 = "http://remoteimage.com/image.jpg"; string url2 = "http://remoteimage.com/image2.jpg"; try { // Check to see if url1 exists or not HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1); request.Credentials = System.Net.CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); myImg.Visible = true; myImg.ImageUrl = url1; } catch (Exception ex) { // Check to see if url2exists or not HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url2); request.Credentials = System.Net.CredentialCache.DefaultCredentials; HttpWebResponse response; try { response = request.GetResponse() as HttpWebResponse; } catch (WebException exc) { response = exc.Response as HttpWebResponse; } // Set myImg to show if url2 exists myImg.Visible = true; myImg.ImageUrl = url2; // If response returns 404, then hide myImg if (response.StatusCode == HttpStatusCode.NotFound) { myImg.Visible = false; } }

Can't see the comments? Please login first :)