Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file exists on an webserver by its URL?

Tags:

c#

.net

http

in our application we have some kind of online help. It works really simple: If the user clicks on the help button a URL is build depending on the current language and help context (e.g. "http://example.com/help/" + [LANG_ID] + "[HELP_CONTEXT]) and called within the browser.

So my question is: How can i check if a file exists on the web server without loading the complete file content?

Thanks for your Help!

Update: Thanks for your help. My question has been answered. Now we have proxy authentication problems an cannot send the HTTP request ;)

like image 372
Alexander Avatar asked Sep 22 '09 13:09

Alexander


2 Answers

Had the same problem myself and found this question and the answers here really useful.

But the answers here use the old WebRequest-class which is a bit outdated, it has no async support for starters. So I wanted to use the more modern way of doing it with HttpClient. Here is an example with a little helper class to check if the file exist:

using System.Net.Http;
using System.Threading.Tasks;

class HttpClientHelper
{
    private static HttpClient _httpClient;

    public static async Task<bool> DoesFileExist(string url)
    {
        if (_httpClient == null)
        {
            _httpClient = new HttpClient();
        }

        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url))
        {
            using (HttpResponseMessage response = await _httpClient.SendAsync(request))
            {
                return response.StatusCode == System.Net.HttpStatusCode.OK;
            }
        }
    }
}

Usage:

if (await HttpClientHelper.DoesFileExist("https://www.google.com/favicon.ico"))
{
    // Yes it does!  
}
else
{
    // No it doesn't!
}
like image 50
Esko Avatar answered Oct 18 '22 17:10

Esko


You can use .NET to do a HEAD request and then look at the status of the response.

Your code would look something like this (adapted from The Lowly HTTP HEAD Request):

// create the request
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

// instruct the server to return headers only
request.Method = "HEAD";

// make the connection
HttpWebResponse response = request.GetResponse() as HttpWebResponse;

// get the status code
HttpStatusCode status = response.StatusCode;

Here's a list detailing the status codes that can be returned by the StatusCode enumerator.

like image 40
Gavin Miller Avatar answered Oct 18 '22 16:10

Gavin Miller