c#使用WebClient下载文件并保存

本文关键字:保存 文件 下载 使用 WebClient | 更新日期: 2023-09-27 18:21:33

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

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

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

c#使用WebClient下载文件并保存

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

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

虽然Stephens的答案完全正确,但有时可能会不愉快。我想创建一个临时文件名(与Stephen建议的没有太大区别,但在一个临时文件夹中——很可能是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;
    }
    // ...
}