How to check if a file exists on an webserver by i

2020-02-11 02:49发布

问题:

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 ;)

回答1:

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.



回答2:

Can we assume that you are running your web application on the same web server as you are retrieving your help pages from? If yes, then you can use the Server.MapPath method to find a path to the file on the server combined with the File.Exists method from the System.IO namespace to confirm that the file exists.



回答3:

Send a HEAD request for the URL (instead of a GET). The server will return a 404 if it doesn't exist.



回答4:

Take a look at the HttpWebResponse class. You could do something like this:

string url = "http://example.com/help/" + LANG_ID + HELP_CONTEXT;
WebRequest request=WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusDescription=="OK") 
{
   // worked
}


回答5:

If you want to check the status of a document on the server:

function fetchStatus(address) {
 var client = new XMLHttpRequest();
 client.onreadystatechange = function() {
  // in case of network errors this might not give reliable results
  if(this.readyState == 4)
   returnStatus(this.status);
 }
 client.open("HEAD", address);
 client.send();
}

Thank you.



回答6:

EDIT: Apparently a good method to do this would be a HEAD request.

You could also create a server-side application that stores the name of every available web page on the server. Your client application could then query this application and respond a little bit quicker than a full page request, and without throwing a 404 error every time the file doesn't exist.



回答7:

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!
}


标签: c# .net http