How to check remote file exists in ASP.NET

Sometimes we get the requirement to check if a file exists remotely such as javascript or image file.
Suppose you are in server(xxx.com) and you want to check a file in another server(yyy.com) - in this case it will be helpful.
 
The following code snippet describes how to implement it. It can be implement in the following two ways:
 
1. Using HTTPWebRequest:
------------------------------------------------- 
 
private bool RemoteFileExistsUsingHTTP(string url)
{
    try
          {
                 //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 TURE if the Status code == 200
                  return (response.StatusCode == HttpStatusCode.OK);
         }
         catch
         {
                //Any exception will returns false.
                return false;
          }
}
 
2. Using WebClient:
---------------------------------------------------
private bool RemoteFileExistsUsingClient(string url)
{
      bool result = false;
      using (WebClient client = new WebClient())
      {
             try
            {
                    Stream stream = client.OpenRead(url);
                    if (stream != null)
                    {
                           result = true;
                    }
                    else
                    {
                           result = false;
                    }
          }
          catch
          {
                 result = false;
          }
     }
     return result;
}
 
Call Method:
---------------------------------------- 
RemoteFileExistsUsingHTTP("http://localhost:16868/JavaScript1.js");
 
Don't confuse here because it was implemented in two ways. Always use HttpWebRequest class over WebClient because of the following reasons:
 
1. WebClient internally calls HttpWebRequest
2. HttpWebRequest has more options (credential, method) as compared to Webclient
 
Hope it will help you. 
Happy Coding!!