Another Salesforce blog!!!

Salesforce, Apex

Check to see whether the file in a url Exists or Not

You can use HttpWebRequest.

Note four things

1) The webRequest will throw exception if the link doesn’t exist
2) You may like to disable auto redirect
3) You may also like to check if it’s a valid url. If not, it will throw UriFormatException.
4) Per Paige suggested , Use “Head” in request.Method so that it won’t download the whole remote file

private static bool RemoteFileExists(string url)
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = “HEAD”;
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
return (response.StatusCode == HttpStatusCode.OK);
//Any exception will returns false.
return false;

Leave a Reply

Your email address will not be published. Required fields are marked *