Csharp/C#教程:Web客户端DownloadFileCompleted获取文件名分享


Web客户端DownloadFileCompleted获取文件名

我试着像这样下载文件:

WebClient _downloadClient = new WebClient(); _downloadClient.DownloadFileCompleted += DownloadFileCompleted; _downloadClient.DownloadFileAsync(current.url, _filename); // ... 

下载后我需要用下载文件启动另一个进程,我尝试使用DownloadFileCompleted事件。

 void DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (e.Error != null) { throw e.Error; } if (!_downloadFileVersion.Any()) { complited = true; } DownloadFile(); } 

但是,我无法从AsyncCompletedEventArgs知道下载文件的名称,我自己做了

 public class DownloadCompliteEventArgs: EventArgs { private string _fileName; public string fileName { get { return _fileName; } set { _fileName = value; } } public DownloadCompliteEventArgs(string name) { fileName = name; } } 

但我无法理解如何调用我的事件而不是DownloadFileCompleted

对不起,如果它是好问题

一种方法是创建一个闭包。

  WebClient _downloadClient = new WebClient(); _downloadClient.DownloadFileCompleted += DownloadFileCompleted(_filename); _downloadClient.DownloadFileAsync(current.url, _filename); 

这意味着您的DownloadFileCompleted需要返回事件处理程序。

  public AsyncCompletedEventHandler DownloadFileCompleted(string filename) { Action action = (sender,e) => { var _filename = filename; if (e.Error != null) { throw e.Error; } if (!_downloadFileVersion.Any()) { complited = true; } DownloadFile(); }; return new AsyncCompletedEventHandler(action); } 

我创建名为_filename的变量的原因是,传递给DownloadFileComplete方法的文件名变量被捕获并存储在闭包中。 如果你没有这样做,你就无法访问闭包中的filename变量。

我正在玩DownloadFileCompleted来获取文件路径/文件名来自事件。 我也试过上面的解决方案,但这不像我的期望那么我喜欢添加Querystring值的解决方案,在这里我想与你分享代码。

 string fileIdentifier="value to remember"; WebClient webClient = new WebClient(); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCompleted); webClient.QueryString.Add("file", fileIdentifier); // here you can add values webClient.DownloadFileAsync(new Uri((string)dyndwnldfile.path), localFilePath); 

事件可以定义如下:

上述就是C#学习教程:Web客户端DownloadFileCompleted获取文件名分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { string fileIdentifier= ((System.Net.WebClient)(sender)).QueryString["file"]; // process with fileIdentifier } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1008771.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐