winform三十二线程分块下载文件 ----分享

2020-02-07 10:45栏目:竞技宝app
TAG:

龙电竞官网,不想重新写啦..直接看笔者今日头条的稿子吧(不会说本人打广告吧.最讨厌了.卡塔尔(قطر‎最终有源码链接地址

publicclassDownloadThread{privatestringsaveFilePath;privateUridownUrl;privatelongblock;privateintthreadId=-1;privatelongdownLength;privateboolfinish=false;privateFileDownloaderdownloader;publicDownloadThread(FileDownloaderdownloader,UridownUrl,stringsaveFile,longblock,longdownLength,intthreadId){this.downUrl=downUrl;this.saveFilePath=saveFile;this.block=block;this.downloader=downloader;this.threadId=threadId;this.downLength=downLength;}publicvoidThreadRun(){//taskThreadtd=newThread(newThreadStart(()={Console.WriteLine(threadId.ToString()+"start"+downLength.ToString()+""+block.ToString());if(downLengthblock)//未下载完成{try{intstartPos=(int)(block*(threadId-1)+downLength);//开始位置intendPos=(int)(block*threadId-1);//结束位置Console.WriteLine("Thread"+this.threadId+"startdownloadfromposition"+startPos+"andendwith"+endPos);HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(downUrl);request.Referer=downUrl.ToString();request.Method="GET";request.UserAgent="Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;SV1;.NETCLR2.0.1124)";request.AllowAutoRedirect=false;request.ContentType="application/octet-stream";request.Accept="image/gif,image/jpeg,image/pjpeg,image/pjpeg,application/x-shockwave-flash,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-xbap,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*";request.Timeout=10*1000;request.AllowAutoRedirect=true;request.AddRange(startPos,endPos);//Console.WriteLine(request.Headers.ToString());HttpWebResponseresponse=(HttpWebResponse)request.GetResponse();WebResponsewb=request.GetResponse();using(Stream_stream=wb.GetResponseStream()){byte[]buffer=newbyte[1024*50];longoffset=-1;using(Streamthreadfile=newFileStream(this.saveFilePath,FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite)){threadfile.Seek(startPos,SeekOrigin.Begin);while((offset=_stream.Read(buffer,0,buffer.Length))!=0){downloader.append(offset);threadfile.Write(buffer,0,(int)offset);downLength+=offset;downloader.update(this.threadId,downLength);}threadfile.Close();_stream.Close();Console.WriteLine("Thread"+this.threadId+"downloadfinish");this.finish=true;}}}catch(Exceptione){this.downLength=-1;Console.WriteLine("Thread"+this.threadId+":"+e.Message);}}else{Console.WriteLine(downLength);}}));td.IsBackground=true;td.Start();}///summary///下载是否完成////summary///returns/returnspublicboolisFinish(){returnfinish;}///summary///已经下载的内容大小;return如果返回值为-1,代表下载失败////summary///returns/returnspubliclonggetDownLength(){returndownLength;}}

龙电竞官网 1

版权声明:本文由龙竞技官网发布于竞技宝app,转载请注明出处:winform三十二线程分块下载文件 ----分享