using UnityEngine; using System.Collections; using System.Threading; using System.IO; using System.Net; public class ThreadDownLoadFile { //下载地址 public string url; //下载到本地的存入的位置 public string localPath; //检查是否下载完成 public bool isDone = false; public ThreadDownLoadFile(string url,string localPath) { this.url = url; this.localPath = localPath; } //线程工作方法--下载文件 public void DownFile() { long lastDownPos = 0; //检查本地是否 已经有该文件,如果有,则续传 FileStream fs = null; if (File.Exists(localPath)) { fs = File.Open(localPath, FileMode.Append); lastDownPos = fs.Length; } else //如果没有,新建 { fs = File.Create(localPath); } //开始一个线程 //web请求的处理 HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; //是否断点续传 if (lastDownPos > 0) { request.AddRange((int)lastDownPos);//从上次下载的位置开始 读取数据 //从请求对象得到响应对象。从响应对象取得响应数据 using (Stream stream = request.GetResponse().GetResponseStream()) { int nReadSize = 0; do { byte[] buffer = new byte[1024 * 100]; nReadSize = stream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, nReadSize); } while (nReadSize > 0); } fs.Flush(); fs.Close(); isDone = true; } } }
using UnityEngine; using System.Collections; using System.IO; using System.Threading; public class Test : MonoBehaviour { ThreadDownLoadFile downFile = null; // Use this for initialization public void OnGUI() { if (GUILayout.Button("Down")) { //开启线程,开始下载 string url = "http://www.rongweijun.cn"; string localPath= Application.persistentDataPath + "/" + Path.GetFileName(url); downFile = new ThreadDownLoadFile(url, localPath); Thread thread = new Thread(downFile.DownFile); thread.Start(); } if( downFile!=null && downFile.isDone) { GUILayout.Label("OK"); } } }
原文:http://www.cnblogs.com/rongweijun/p/6294477.html