Check if file is newer and then download

0

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

The problem is that these files are available every day on the site, but are updated randomly on a weekly basis, that is, I can not determine on what date these files are updated.

The files always have the same name, then 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 download 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);
        }
    }
    
asked by anonymous 26.11.2014 / 12:53

1 answer

1

You need to make this request without getting the contents of the file. For this you must use the verb head of http.

  

HEAD

     
    

GET variation where the resource is not returned. It is used to get metadata through the response header, without having to retrieve all content.
link

  

The low operation checks if 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 modified date of the old file to test for any changes.

    
27.11.2014 / 17:56