【问题标题】:WebClient.DownloadFileAsync preserving Last modified dateWebClient.DownloadFileAsync 保留上次修改日期
【发布时间】:2014-06-19 16:39:10
【问题描述】:

我正在使用WebClient.DownloadFileAsync 方法从远程服务器通过 Windows 应用程序连接到我的本地计算机。我可以使用上述方法下载文件,但问题是文件在服务器上的“上次修改日期”在下载到我的机器时被修改为当前日期和时间。通过 Fiddler 下载文件时,我可以在文件的响应标头中看到上次修改日期。您能帮我保留文件的最后修改日期吗:我正在使用以下代码:

 // Create a web client
        using (var client = new IfModifiedSinceWebClient())
        {
            client.IfModifiedSince = File.GetLastWriteTimeUtc(path);


            // Initiate an asynchronous download to a temporary file
            var downloadPath = Path.GetTempFileName();
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(UpdateFileIfNewerDownloadFileCompleted);
            client.DownloadFileAsync(uri, downloadPath, new UpdateFileIfNewerState(path, downloadPath, onComplete));
        }

【问题讨论】:

    标签: c# asynchronous download


    【解决方案1】:

    这是我在同步下载时的做法。

    File.SetLastWriteTime(filename, client.ResponseHeaders("Last-Modified"))
    

    【讨论】:

      【解决方案2】:

      如果有人仍然对可行的解决方案感兴趣:

          public static Task DownloadFileHttp(Uri url, string localPath)
          {
              using (var client = new WebClient()) {
                  client.Proxy = WebRequest.DefaultWebProxy;
                  client.DownloadFileCompleted +=
                       (sender, e) => {
                           SetLastModified(localPath, sender as WebClient);
                       };
      
                  return client.DownloadFileTaskAsync(url, localPath);
              }
          }
      
          private static void SetLastModified(string localPath, WebClient w)
          {
              var lastModified = w.ResponseHeaders["Last-Modified"];
              if (DateTime.TryParse(lastModified, out DateTime date))
                  File.SetLastWriteTime(localPath, date);
          }
      

      【讨论】:

        猜你喜欢
        • 2016-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        • 2019-11-14
        相关资源
        最近更新 更多