C#文件断点续传实现方法
本文实例讲述了C#文件断点续传实现方法。分享给大家供大家参考。具体实现方法如下:
///<summary> ///下载局域网文件 ///</summary> ///<paramname="path">文件路径,如:\\192.168.10.1\app\app\123.zip</param> ///<paramname="username">计算机名称</param> ///<paramname="password">计算机密码</param> staticvoidRequestWindowsShared(stringpath,stringusername,stringpassword) { //文件总大小 intallBytesCount=0; //每次传输大小 intbyteTemp=1024; //当前位置 intbytePosition=0; //剩下大小 intremain=0; System.Net.FileWebRequestrequest=null; System.Net.FileWebResponseresponse=null; System.IO.Streamstream=null; System.IO.FileStreamfileStream=null; try { Uriuri=newUri(path); request=(System.Net.FileWebRequest)System.Net.FileWebRequest.Create(uri); System.Net.ICredentialsic=newSystem.Net.NetworkCredential(username,password); request.Credentials=ic; response=(System.Net.FileWebResponse)request.GetResponse(); stream=response.GetResponseStream(); byte[]bytes=newbyte[stream.Length]; stream.Read(bytes,0,bytes.Length); stringfilename=System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\"+System.IO.Path.GetFileName(path); fileStream=newFileStream(filename,System.IO.FileMode.Create,System.IO.FileAccess.Write,System.IO.FileShare.ReadWrite); allBytesCount=bytes.Length; remain=allBytesCount; while(remain>0) { fileStream.Write(bytes,bytePosition,byteTemp); remain=remain-byteTemp; bytePosition=bytePosition+byteTemp; fileStream.Flush(); if(remain<byteTemp) byteTemp=remain; } Console.WriteLine("下载成功!"); } catch(Exceptionex) { Console.WriteLine(ex.Message); } finally { fileStream.Close(); fileStream.Dispose(); stream.Close(); stream.Dispose(); } } ///<summary> ///上传文件 ///</summary> ///<paramname="path">共享目录路径+文件名称</param> ///<paramname="local">本地路径</param> ///<paramname="username">用户名</param> ///<paramname="password">密码</param> staticvoidResponseWindowsShared(stringpath,stringlocal,stringusername,stringpassword) { //文件总大小 intallBytesCount=0; //每次传输大小 intbyteTemp=1024; //当前位置 intbytePosition=0; //剩下大小 intremain=0; System.Net.FileWebRequestrequest=null; System.IO.Streamstream=null; try { //时间戳 stringstrBoundary="----------"+DateTime.Now.Ticks.ToString("x"); Uriuri=newUri(path); byte[]bytes=System.IO.File.ReadAllBytes(local); request=(System.Net.FileWebRequest)System.Net.FileWebRequest.Create(uri); request.Method="POST"; //设置获得响应的超时时间(300秒) request.Timeout=300000; request.ContentType="multipart/form-data;boundary="+strBoundary; request.ContentLength=bytes.Length; System.Net.ICredentialsic=newSystem.Net.NetworkCredential(username,password); request.Credentials=ic; stream=request.GetRequestStream(); allBytesCount=bytes.Length; remain=allBytesCount; while(remain>0) { stream.Write(bytes,bytePosition,byteTemp); remain=remain-byteTemp; bytePosition=bytePosition+byteTemp; stream.Flush(); if(remain<byteTemp) byteTemp=remain; } Console.WriteLine("上传成功!"); } catch(Exceptionex) { Console.WriteLine(ex.Message); } finally { stream.Close(); stream.Dispose(); } }
希望本文所述对大家的C#程序设计有所帮助。