Check if file is newer and then download

Asked

Viewed 541 times

1

I created a windows service, which daily downloads some files. These files have about 2Gb (that’s right, two gigabytes!).

The problem is that these files are every day available on the site, but are updated randomly weekly, IE, I can not determine when these files are updated.

Files always have the same name, so the same url.

How can I check if the file on the site is newer than the file I’ve already downloaded?

The intention is not to keep downloading the files unnecessarily.

Below my download function :

 private void FazDownload(string fileUrlToDownload, string Saida)
    {
        WebRequest getRequest = WebRequest.Create(fileUrlToDownload);

        getRequest.Headers.Add("Cookie", CookieAutenticacao);
        try
        {
            using (WebResponse getResponse = getRequest.GetResponse())
            {
                log.Info("Fazendo download de " + fileUrlToDownload);

                string OutPutfileFullPath = Saida;

                #region Se não existir o diretório então cria o diretório.
                if (!Directory.Exists(Path.GetDirectoryName(OutPutfileFullPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(OutPutfileFullPath));
                }
                #endregion

                using (var fileStream = File.Create(OutPutfileFullPath, 8092))
                {
                    getResponse.GetResponseStream().CopyTo(fileStream);//Download e escrita em arquivo.
                }

                log.Info(String.Format("Download de {0} realizado com sucesso e gravado em {1}.", fileUrlToDownload, OutPutfileFullPath));
            }
        }
        catch (System.Net.WebException)
        {
            log.Warn("Arquivo não encontrado em " + fileUrlToDownload);
        }
    }
  • There is no way for you to get the file’s HASH and compare with what you have on the user’s pc?

1 answer

1


You need to make that request without getting the file contents. To do this you must use the http head verb.

HEAD

Variation of GET where the resource is not returned. It is used to get meta-information through the response header without having to recover all the content.
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

The operation below checks whether the file has changed since a certain date

 public bool Modificado(String url, DateTime desde)
 {
        var request = HttpWebRequest.Create(url) as HttpWebRequest;            
        request.Method = "Head";
        request.AllowAutoRedirect = false;      
        request.IfModifiedSince = desde;            
        using (var response = request.GetResponse() as HttpWebResponse)
        {
            return response.StatusCode != HttpStatusCode.NotModified;
        }
 }

You can use the last modification date of the old file to test for any changes.

Browser other questions tagged

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