You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WPF中WebClient的DownloadFileCompleted事件如何获取已下载文件信息

解决方案

你可以通过WebClient.DownloadFileTaskAsync的userToken重载实现需求,该参数支持传入任意自定义数据,会在下载完成后通过DownloadFileCompleted事件的e.UserState属性原路返回。


修改步骤

1. 调整DownloadAsync方法,传入自定义状态

调用下载方法时,将Radar文件的本地存储路径作为userToken传入,修改后的核心代码如下:

private async Task DownloadAsync(WebClient Client)
{
    for (int i = 0; i < urls.Count; i++)
    {
        stopwatch.Start();
        string extractFile = Path.Combine(textBoxSatelliteFolder.Text, "extractFile.txt");
        string fNameRad = Path.Combine(textBoxRadarFolder.Text, $"radImage{countRad}.gif");
        string fNameSat = Path.Combine(textBoxSatelliteFolder.Text, $"satImage{countSat}.gif");
        
        if (urls[i] == "https://myimage.com/")
        {
            // 可选传入普通文件路径作为token
            await Client.DownloadFileTaskAsync(new Uri(urls[i]), extractFile, extractFile);
        }
        else
        {
            if (urls[i].Contains("Radar"))
            {
                // 第三个参数传入Radar文件本地路径作为自定义token
                await Client.DownloadFileTaskAsync(new Uri(urls[i]), fNameRad, fNameRad);
                countRad++;
            }
            else
            {
                // 可选传入卫星文件路径作为token
                await Client.DownloadFileTaskAsync(new Uri(urls[i]), fNameSat, fNameSat);
                countSat++;
            }
        }
    }
}

补充:代码中用Path.Combine拼接路径替代硬编码斜杠,避免不同系统/路径格式下的兼容问题。

2. 调整OnDownloadFileComplete事件,获取文件路径

下载完成无错误时,直接从e.UserState中取出路径执行后续操作,修改后的核心代码如下:

private async void OnDownloadFileComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    lblProgress.Content = "下载完成!";
    stopwatch.Reset();
    btnDownloadFile.IsEnabled = true;
    
    // 新增空判断避免空引用异常
    if(e.Error == null && e.UserState != null)
    {
        string downloadFilePath = e.UserState.ToString();
        urlsCounter--;
        lblMumberOfFiles.Content = urlsCounter;
        
        // 判断是否为Radar类型图片
        if (downloadFilePath.Contains("Radar"))
        {
            // 直接使用获取到的实际路径执行文件操作,不需要写死路径
            drawonimage.DrawText(datesonimages[0].ToString(), downloadFilePath);
        }
    }
    
    // 原有其他逻辑保持不变
    if (extractOnce == false)
    {
        radar.GetRadarImages();
        await Task.Delay(5000);
        for (int i = 0; i < radar.links.Count; i++)
        {
            urls.Add(radar.links[i]);
        }
        dates = radar.dates;
        foreach(var date in dates)
        {
            datesonimages.Add(date.ToString("ddd, dd MMM yyy HH':'mm"));
        }
        ExtractLinks();
        extractOnce = true;
    }
}

扩展说明

如果需要传递更多下载相关信息(比如文件类型标识、下载序号、对应拍摄时间等),可以自定义一个简单的数据类封装信息后作为userToken传入,使用时强转即可,示例如下:

// 自定义下载信息类
public class DownloadItemInfo
{
    public string FilePath { get; set; }
    public string FileType { get; set; }
    public DateTime ShootTime { get; set; }
}

// 传入时构造对象
await Client.DownloadFileTaskAsync(new Uri(urls[i]), fNameRad, new DownloadItemInfo
{
    FilePath = fNameRad,
    FileType = "Radar",
    ShootTime = datesonimages[0]
});

// 事件中取出使用
var info = e.UserState as DownloadItemInfo;
if(info != null && info.FileType == "Radar")
{
    drawonimage.DrawText(info.ShootTime.ToString("ddd, dd MMM yyy HH':'mm"), info.FilePath);
}

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:54:04