Home > .Net, Visual Studio > How to check remote file exists using C#

How to check remote file exists using C#

Sometime you require to display remote images in the Web Pages, like Ads, Banner etc, it may be from different domain or a different application. This code will help you to check the existence of a Remote file using C#.

using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(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;
    }
}

You can also use WebClient class for the same purpose. Like this.

using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(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
        {
            //Any exception will returns false.
            result = false;
        }
    }
    return result;
}

Internally WebClient is using the HttpWebRequest and HttpWebResponse classes, so it is good to use the first method.

  1. No comments yet.
  1. No trackbacks yet.