WebClient下载文件的简单使用

1、先加一些using;

using System;
using System.Net;
using System.Collections;

2、结合协成开始进行下载;

    IEnumerator StartDownload(string url, Action onProgress, Action 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));
    }

这样就满足我们简单的下载文件的需求了

如有雷同,纯属巧合

你可能感兴趣的:(C#语言,WebClient,Download)