WebClient下載文件的簡單使用

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));
    }

這樣就滿足我們簡單的下載文件的需求了

如有雷同,純屬巧合

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章