How to know if a file exists through its url without needing to download it?

Asked

Viewed 130 times

1

I have a file list, and I need to know if it was uploaded to a storage facility. The idea to facilitate the process is to concatenate the file name, generate a URL and try to download the file, if it returns 404 my method returns false.

public static bool ThumbExist(string contributorID,string imageID)
{
    string url = String.Format("https://servico.com/file/{0}/{1}.jpg", contributorID, imageID);
    byte[] myDataBuffer;
    WebClient myWebClient = new WebClient();
    myWebClient.Headers.Add("User-Agent: Other");
    try
    {
        myDataBuffer = myWebClient.DownloadData(url);
        return true;
    }
    catch (Exception e) //Quando não existe o servidor retorna um 404 e cai aqui
    {
        return false;
    }
}

How can I verify ONLY if the server returns me at least 1 byte without having to download the whole image.

I need this because if the image exists, my code downloads it completely and it takes unnecessary time.

1 answer

0


Using Webrequest instead of Webclient can check the file size.

Example:

WebRequest request = WebRequest.Create(new Uri("http://www.example.com/"));
request.Method = "HEAD";

using(WebResponse response = request.GetResponse()) {
    Console.WriteLine("{0} {1}", response.ContentLength, response.ContentType);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.