How to check remote file exists using C#

Standard

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.


  • Utku Feruz

    This one really helped me a lot.I’m just wondering Is it possible to use File.Exists() instead of web request? Seems like you can’t reach the remote server with that.

    • http://www.dotnetthoughts.net/ Anuraj P

      No, you can’t use File.Exists it will work on local file system only.

  • SAM

    First, thanks for your post. It really helped me.

    You can imagine a use case where you have 100s or 1000s of URLs that you want to check. For me it is 700+ image files, but it could be FAQs, product landing pages, or any other case where the URLs can be generated from a database query or file system script.

    What I did was put all of my URLs into a text file (MyLinks.txt). It looks like this:

    http://foo.org/foo/Images/Normal/1598_1_CR.jpg
    http://foo.org/foo//Images/Normal/2.jpg
    http://foo.org/foo/Images/Normal/31796.2001.jpg
    http://foo.org/foo/Images/Normal/4.2001.jpg
    etc….

    I built a console app that goes through each URL in the file then check it with the code in this blog. The entire thing is below. I am amazed that I couldn’t find an example of this and I was going to make a CodeProject articlee out of it, but it seems more appropriate to put it here. Thanks again.

    Steve

    PS, One thing that is really important to do is add “response.Close()” which I did below. It is also a good idea to put in a request.Timeout value.

    using System;
    using System.Net;
    using System.IO;

    namespace LinkChecker
    {
    class Program
    {
    static void Main(string[] args)
    {

    string[] m_urls = File.ReadAllLines(@”C:\LinkChecker\MyLinks.txt”);

    //string[] m_urls = new string[] { m_arraystring.ToString() };

    StreamWriter m_results = new StreamWriter(@”C:\LinkChecker\LinkCheckerResults.txt”, true);

    // Print length of each row
    for (int i = 0; i < m_urls.Length; i++)
    {
    Console.WriteLine("Status of URL " + m_urls[i].ToString() + " is " + RemoteFileExists(m_urls[i]));
    m_results.WriteLine("Status of URL " + m_urls[i].ToString() + " is " + RemoteFileExists(m_urls[i]));
    m_results.Flush();
    }

    }

    ///
    /// Checks the file exists or not.
    ///
    /// The URL of the remote file.
    /// True : If the file exits, False if file not exists
    public static 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";
    request.Timeout = 10000;
    //Getting the Web Response.
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    response.Close();
    //Returns TURE if the Status code == 200
    return (response.StatusCode == HttpStatusCode.OK);

    }
    catch
    {
    //Any exception will returns false.
    return false;
    }
    }

    }

  • Matt

    This is great.

    I was wondering if a proxy server would cause the HttpWebResponse to return “not found”.

    If so, would you have an idea on how to pass along current users credentials to the proxy server to allow the request to pass?

  • http://google.com hemant

    nice code, thanks dude

  • Naresh

    Hi.. How to check the url in windows phone 7? I use the same code. But it shows errors.
    Please tell me how to use this in windows phone 7??

    • http://www.dotnetthoughts.net Anuraj P

      You can try async version to do the same. Because WP7 doesn’t support sync version of the apis.