【问题标题】:c# downloading file with WebClient and saving itc#使用WebClient下载文件并保存
【发布时间】:2015-11-11 19:31:58
【问题描述】:

我有下载文件的代码,它只是替换它。

    WebClient webClient = new WebClient();
    {
          webClient.DownloadFile("http://test.png", "C:\PNG.png")
    } 

我只是想知道,是否可以下载文件,然后保存文件而不是替换旧文件(在上面的示例中为 png.png)。

【问题讨论】:

  • 您将其以相同的名称保存到相同的位置,每次都会替换它。只需使用不同的名称。
  • 在下载之前,请检查它是否存在。如果没有下载。如果它确实做了不同的事情(使用不同的名称)
  • 抱歉,我忘了。
  • @MarshallOfSound 这种方法可能会给您带来麻烦。只需考虑使用这种方法处理较大文件的两个线程。第一个线程看到没有名为 like 的文件,开始下载,然后第二个线程开始运行,看到没有文件名 like(但是 - 因为线程 1 没有完成下载),然后开始下载文件名。
  • 然后在下载开始前制作一个占位符文件。使用该文件名但完全为空

标签: c#


【解决方案1】:

每次创建一个唯一的名称。

WebClient webClient = new WebClient();
{
    webClient.DownloadFile("http://test.png", string.Format("C:\{0}.png", Guid.NewGuid().ToString()))
} 

【讨论】:

    【解决方案2】:

    虽然斯蒂芬斯的回答完全有效,但这有时可能并不方便。我想创建一个临时文件名(这与斯蒂芬提议的没有什么不同,但在一个临时文件夹中 - 很可能是 AppData/Local/Temp)并在下载完成后重命名文件。这个类演示了这个想法,我还没有验证它是否按预期工作,但如果它确实可以随意使用这个类。

    class CopyDownloader
    {
        public string RemoteFileUrl { get; set; }
        public string LocalFileName { get; set; }
        WebClient webClient = new WebClient();
    
        public CopyDownloader()
        {
            webClient.DownloadFileCompleted += WebClientOnDownloadFileCompleted;
        }
    
        public void StartDownload()
        {
            var tempFileName = Path.GetTempFileName();
            webClient.DownloadFile(RemoteFileUrl, tempFileName, tempFileName)
        }
    
        private void WebClientOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
        {
            string tempFileName = asyncCompletedEventArgs.UserState as string;
            File.Copy(tempFileName, GetUniqueFileName());
        }
    
        private string GetUniqueFilename()
        {
            // Create an unused filename based on your original local filename or the remote filename
        }
    }
    

    如果您想显示进度,您可能会公开一个事件,该事件会在引发 WebClient.DownloadProgressChanged 时发出

    class CopyDownloader
    {
        public event DownloadProgressChangedEventHandler ProgressChanged;
    
        private void WebClientOnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs downloadProgressChangedEventArgs)
        {
            if(ProgressChanged != null)
            {
                ProgressChanged(this, downloadProgressChangedEventArgs);
            }
        }
    
        public CopyDownloader()
        {
             webClient.DownloadFileCompleted += WebClientOnDownloadFileCompleted;
             webClient.DownloadProgressChanged += WebClientOnDownloadProgressChanged;
        }
    
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 2017-03-09
      相关资源
      最近更新 更多