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 Download()
{
long lastDownPos = 0;
//检查本地是否已经有该文件,如果有,续传
FileStream fs;
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;
}
ThreadDownloadFile downFile = null;
string localPath;
public void OnGUI()
{
if (GUILayout.Button("Download"))
{
string url = "http://xiazai.xiazaiba.com/Soft/F/FSCapture_8.4_XiaZaiBa.zip";
localPath = Application.persistentDataPath+"/"+Path.GetFileName(url);
downFile = new ThreadDownloadFile(url, localPath);
//开启一个线程,做文件下载
Thread thread = new Thread(downFile.Download);
//启动线程
thread.Start();
}
if (downFile!=null&&downFile.isDone)
{
GUILayout.Label("Complete");
//print(localPath);
}
}
使用多线程创建下载任务
最新推荐文章于 2024-03-10 23:38:03 发布