问题描述
stringStrFileName=@"D:测试C#断点续传DownLoad军情观察室20070620.rmvb";//根据实际情况设置stringStrUrl="http://localhost:2155/断点续传/DataSource/军情观察室20070620.rmvb";//根据实际情况设置//打开上次下载的文件或新建文件longlStartPos=0;System.IO.FileStreamfs;if(System.IO.File.Exists(StrFileName)){fs=System.IO.File.OpenWrite(StrFileName);lStartPos=fs.Length;fs.Seek(lStartPos,System.IO.SeekOrigin.Current);//移动文件流中的当前指针}else{fs=newSystem.IO.FileStream(StrFileName,System.IO.FileMode.Create);lStartPos=0;}//打开网络连接try{System.Net.HttpWebRequestrequest=(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);request.Headers.Add("Accept-Ranges","bytes");//doublefilesize=request.GetResponse().ContentLength;if(lStartPos>0)request.AddRange((int)lStartPos);//设置Range值//向服务器请求,获得服务器回应数据流System.Net.WebResponseresponse=(System.Net.WebResponse)request.GetResponse();response.Headers.Add("Accept-Ranges","bytes");//longlength=response.ContentLength;System.IO.Streamns=response.GetResponseStream();stringtemp=response.Headers["Accept-Ranges"].ToString();byte[]nbytes=newbyte[512];intnReadSize=0;nReadSize=ns.Read(nbytes,0,512);while(nReadSize>0){fs.Write(nbytes,0,nReadSize);nReadSize=ns.Read(nbytes,0,512);}fs.Close();ns.Close();Console.WriteLine("下载完成");}catch(Exceptionex){fs.Close();Console.WriteLine("下载过程中出现错误:"+ex.ToString());}