using System;
using System.ComponentModel;
using System.Net;
using UnityEngine;public class TestDownloadBehaviour_http : MonoBehaviour
{public string RemoteFileURI;public string SaveFilePath;// Start is called before the first frame updatevoid Start(){DownloadFile();}// Update is called once per framevoid DownloadFile(){using (WebClient wc = new WebClient()){try{wc.Proxy = null;Uri address = new Uri(RemoteFileURI);//调用DownloadFile方法下载文件// wc.DownloadFile(textBox1.Text.ToString(), textBox2.Text.ToString());//调用DownloadFileAsync异步下载文件wc.DownloadFileAsync(address, Application.dataPath + "/" + SaveFilePath);wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(OnDownloadProgessChanged);//下载完成的响应事件wc.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadFileComplited);}catch (Exception ex){Debug.LogError(ex.Message);}}}void OnDownloadProgessChanged(object sender, DownloadProgressChangedEventArgs e){Debug.LogFormat("progress = {0}, total = {1}, received = {2}", e.ProgressPercentage, e.TotalBytesToReceive, e.BytesReceived);}void OnDownloadFileComplited(object sender, AsyncCompletedEventArgs e){Debug.LogFormat("下载完成");}
}
FTP下载文件:
using System;
using System.ComponentModel;
using System.Net;
using UnityEngine;public class TestDownloadBehaviour : MonoBehaviour
{public string RemoteFileURI;public string SaveFilePath;long _FileSize; // FTP下载时,无法获取到整个文件Size。所以提前调用WEB API来获取Size,然后进行下载。// Start is called before the first frame updatevoid Start(){DownloadFile();}// Update is called once per framevoid DownloadFile(){FtpWebRequest f = WebRequest.Create(RemoteFileURI) as FtpWebRequest;f.Method = WebRequestMethods.Ftp.GetFileSize;FtpWebResponse fr = f.GetResponse() as FtpWebResponse;_FileSize = fr.ContentLength;fr.Close();using (WebClient wc = new WebClient()){try{wc.Proxy = null;Uri address = new Uri(RemoteFileURI);//调用DownloadFile方法下载文件// wc.DownloadFile(textBox1.Text.ToString(), textBox2.Text.ToString());//调用DownloadFileAsync异步下载文件wc.DownloadFileAsync(address, Application.dataPath + "/" + SaveFilePath);wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(OnDownloadProgessChanged);//下载完成的响应事件wc.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadFileComplited);}catch (Exception ex){Debug.LogError(ex.Message);}}}void OnDownloadProgessChanged(object sender, DownloadProgressChangedEventArgs e){Debug.LogFormat("progress = {0}, total = {1}, received = {2}", (float)e.BytesReceived / _FileSize, _FileSize, e.BytesReceived);}void OnDownloadFileComplited(object sender, AsyncCompletedEventArgs e){Debug.LogFormat("下载完成");}
}