WebClient下载文件的简单使用
程序员文章站
2023-12-30 16:57:16
...
1、先加一些using;
using System;
using System.Net;
using System.Collections;
2、结合协成开始进行下载;
IEnumerator StartDownload(string url, Action<int, int, int> onProgress, Action<string> onComplete) {
int bytesReceived = 0;
int totalBytesReceived = 0;
int progressPercentage = 0;
DownloadDataCompletedEventArgs downloadCompletedEvent = null;
var client = new WebClient();
client.DownloadDataCompleted += (sender, evt)=>{ downloadCompletedEvent = evt; };
client.DownloadProgressChanged += (sender, evt)=>{
bytesReceived = (int)evt.BytesReceived;
totalBytesReceived = (int)evt.TotalBytesToReceive;
progressPercentage = evt.ProgressPercentage;
};
client.DownloadDataAsync(new Uri(url));
while (downloadCompletedEvent == null) {
onProgress(bytesReceived, totalBytesReceived, progressPercentage);
yield return new WaitForSeconds(0.02f);
}
yield return new WaitForSeconds(0.6f);
if(downloadCompletedEvent.Error != null) {
onComplete(downloadCompletedEvent.Error.Message);
yield break;
}
onComplete(null);
}
3、每次更新的进度信息回调;
void UpdateProgress(int bytesReceived, int totalBytesReceived, int progressPercentage) {
}
4、下载结束回调;
void DownCompleted(string errorMsg) {
if(string.IsNullOrEmpty(errorMsg)) {
Debug.Log("Download Success");
} else {
Debug.Log("Download Error:" + errorMsg);
}
}
5、开始启动下载方法;
public void Download(string url) {
StartCoroutine(StartDownload(url, UpdateProgress, DownCompleted));
}
这样就满足我们简单的下载文件的需求了
如有雷同,纯属巧合