can I check if a file exists at a URL?

C#File Io

C# Problem Overview


I know I can locally, on my filesystem, check if a file exists:

if(File.Exists(path))

Can I check at a particular remote URL?

C# Solutions


Solution 1 - C#

If you're attempting to verify the existence of a web resource, I would recommend using the HttpWebRequest class. This will allow you to send a HEAD request to the URL in question. Only the response headers will be returned, even if the resource exists.

var url = "http://www.domain.com/image.png";
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";


try
{
    response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    /* A WebException will be thrown if the status of the response is not `200 OK` */
}
finally
{
    // Don't forget to close your response.
    if (response != null)
    {
        response.Close();
    }
}

Of course, if you want to download the resource if it exists it would most likely be more efficient to send a GET request instead (by not setting the Method property to "HEAD", or by using the WebClient class).

Solution 2 - C#

If you want to just copy & paste Justin's code and get a method to use, here's how I've implemented it:

using System.Net;

public class MyClass {
	static public bool URLExists (string url) {
		bool result = false;
		
		WebRequest webRequest = WebRequest.Create(url);
		webRequest.Timeout = 1200; // miliseconds
		webRequest.Method = "HEAD";

		HttpWebResponse response = null;

		try {
			response = (HttpWebResponse)webRequest.GetResponse();
			result = true;
		} catch (WebException webException) {
			Debug.Log(url +" doesn't exist: "+ webException.Message);
		} finally {
			if (response != null) {
				response.Close();
			}
		}
		
		return result;
	}
}

I'll keep his observation:

> If you want to download the resource, and it exists, it would be more efficient to send a GET request instead by not setting the Method property to "HEAD" or by using the WebClient class.

Solution 3 - C#

Below is a simplified version of the code:

public bool URLExists(string url)
{
    bool result = true;

    WebRequest webRequest = WebRequest.Create(url);
    webRequest.Timeout = 1200; // miliseconds
    webRequest.Method = "HEAD";

    try
    {
        webRequest.GetResponse();
    }
    catch
    {
        result = false;
    }

    return result;
}

Solution 4 - C#

If you are using a unc path or a mapped drive, this will work fine.

If you are using a web address (http, ftp etc) you are better off using WebClient - you will get a WebException if it doesn't exist.

Solution 5 - C#

public static bool UrlExists(string file)
    {
        bool exists = false;
        HttpWebResponse response = null;
        var request = (HttpWebRequest)WebRequest.Create(file);
        request.Method = "HEAD";
        request.Timeout = 5000; // milliseconds
        request.AllowAutoRedirect = false;

        try
        {
            response = (HttpWebResponse)request.GetResponse();
            exists = response.StatusCode == HttpStatusCode.OK;
        }
        catch
        {
            exists = false;
        }
        finally
        {
            // close your response.
            if (response != null)
                response.Close();
        }
        return exists;
    }

Solution 6 - C#

I had the same problem to solve in asp.net core, I've solved with HttpClient

private async Task<bool> isFileExist(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                var restponse = await client.GetAsync(url);

               return restponse.StatusCode == System.Net.HttpStatusCode.OK;
            }
        }

Solution 7 - C#

My version:

	public bool IsUrlExist(string url, int timeOutMs = 1000)
	{
		WebRequest webRequest = WebRequest.Create(url);
		webRequest.Method = "HEAD";
		webRequest.Timeout = timeOutMs;
		
		try
		{
			var response = webRequest.GetResponse();
			/* response is `200 OK` */
			response.Close();
		}
		catch
		{
			/* Any other response */
			return false;
		}

		return true;
	}

Solution 8 - C#

WebRequest will waiting long time(ignore the timeout user set) because not set proxy, so I change to use RestSharp to do this.

var client = new RestClient(url);
var request = new RestRequest(Method.HEAD);

 request.Timeout = 5000;
 var response = client.Execute(request);
 result = response.StatusCode == HttpStatusCode.OK;

Solution 9 - C#

Thanks for all answers. And I would like to add my implementation which includes default state when we get errors, for specific cases like mine.

private bool HTTP_URLExists(String vstrURL, bool vResErrorDefault = false, int vTimeOut = 1200)
{
   bool vResult = false;
   WebRequest webRequest = WebRequest.Create(vstrURL);
   webRequest.Timeout = vTimeOut; // miliseconds
   webRequest.Method = "HEAD";
   HttpWebResponse response = null;
   try
   {
      response = (HttpWebResponse)webRequest.GetResponse();
      if (response.StatusCode == HttpStatusCode.OK) vResult = true;
      else if (response.StatusCode == HttpStatusCode.NotFound) vResult = false;
      else vResult = vResErrorDefault;
   }
       catch (WebException ex)
           {
           
              if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
              {
                  var resp01 = (HttpWebResponse)ex.Response;
                  if (resp01.StatusCode == HttpStatusCode.NotFound)
                  {
                      vResult = false;
                  }
                  else
                     {
                         vResult = vResErrorDefault;
                     }
                 }
                 else
                     {
                         vResult = vResErrorDefault;
                     }
                 }
           finally
           {
               // Don't forget to close your response.
               if (response != null)
               {
                   response.Close();
               }
           }
           return vResult;
}

Solution 10 - C#

Anoter version with define timeout :

public bool URLExists(string url,int timeout = 5000)
{
    ...
    webRequest.Timeout = timeout; // miliseconds
    ...
}

Solution 11 - C#

This works for me:

bool HaveFile(string url)
        {
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadString(url);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        } 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmrblahView Question on Stackoverflow
Solution 1 - C#Justin RusbatchView Answer on Stackoverflow
Solution 2 - C#cregoxView Answer on Stackoverflow
Solution 3 - C#Kavit TrivediView Answer on Stackoverflow
Solution 4 - C#OdedView Answer on Stackoverflow
Solution 5 - C#LastEndView Answer on Stackoverflow
Solution 6 - C#Mofaggol HoshenView Answer on Stackoverflow
Solution 7 - C#AndrewView Answer on Stackoverflow
Solution 8 - C#napView Answer on Stackoverflow
Solution 9 - C#S. KızıltoprakView Answer on Stackoverflow
Solution 10 - C#azouinView Answer on Stackoverflow
Solution 11 - C#SilverStitchView Answer on Stackoverflow