Search code examples
c#functionasp.net-mvc-5content-typefile-exists

Does a web file exist - using same function to get the Content Type


I have a function that is coded to get the Content-Type of a web file.

Here is the function:

public string GetContentTypeOfUri(string uri)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "HEAD";
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            var contentType = response.Headers["Content-Type"];
            return (contentType);
        }
    }
    catch (Exception ex)
    {
        return "error";
    }
}

Rather than writing a whole different function to detect if a web file exists, how can I calculate if a file exists from the same code as used to get the Content-Type?

If I use a uri of a file that does not exist, an exception occurs. The ex.HResult equals -2146233079 when this exception occurs, with a message = "The remote name could not be resolved: '[address name]'".

Is it safe to say that when an exception occurs, and the ex.HResult equals -2146233079, the file does not exist?

Is there an easier/better way to work this out?

Thanks in advance

EDIT

Here is the HttpClient code that I have:

public async Task<string> GetContentTypeAsync(string uri)
{
    using (var httpClient = new HttpClient())
    {
        var request = new HttpRequestMessage(HttpMethod.Post, uri);
        request.Method = new HttpMethod("HEAD");
        var response = await httpClient.SendAsync(request);
        string contentType = response.Content.Headers.ContentType.ToString();
        return contentType;
    }
}

Your example web address does inform me that the address does not exist, however, if I have a web address that does not exist such as http://www.usa.canon.com/app/html/HDV/HG10/images/hg10_sample_image_03.jpg5, I am getting a StatusCode of OK, as a Text content type is returned as a custom error page.


Solution

  • There are two possible "not exists" scenarios. It sounds like you've identified one of them - when the server name in the URL is incorrect and so the request cannot even be sent.

    But you're not accounting for the other error - that you can reach a remote server but it denies all knowledge of a specific file. For that scenario, you ought to be checking for status 404 on the response.

    For cleaner handling of your current scenario (server doesn't exist) you could use the Uri class to extract the Host name from the uri string and perform a manual DNS lookup - which would allow you to code for this likely scenario without having to catch exceptions - which is generally frowned upon when its an expected scenario.