类代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; namespace ConsoleTest { class FtpDlder { public void download(String url, String localFile) { FtpWebRequest remoteFileLenReq; // 此请求是为了获取远程文件长度 FtpWebRequest remoteFileReadReq;// 此请求是为了读取文件 Stream readStream = null; // 读取流 FileStream writeStream = null; // 写本地文件流 try { writeStream = new FileStream(localFile, FileMode.Append); long startPosition=writeStream.Length;// 读出本地文件已有长度 // 下面代码目的是取远程文件长度 remoteFileLenReq = (FtpWebRequest)FtpWebRequest.Create(url); remoteFileLenReq.UseBinary = true; remoteFileLenReq.ContentOffset = 0; remoteFileLenReq.Method = WebRequestMethods.Ftp.GetFileSize; FtpWebResponse rsp = (FtpWebResponse)remoteFileLenReq.GetResponse(); long totalByte = rsp.ContentLength; rsp.Close(); if (startPosition >= totalByte) { System.Console.WriteLine("本地文件长度" + startPosition + "已经大于等于远程文件长度" + totalByte); writeStream.Close(); return; } // 初始化读取远程文件请求 remoteFileReadReq = (FtpWebRequest)FtpWebRequest.Create(url); remoteFileReadReq.UseBinary = true; remoteFileReadReq.KeepAlive = false; remoteFileReadReq.ContentOffset = startPosition; remoteFileReadReq.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse response = (FtpWebResponse)remoteFileReadReq.GetResponse(); readStream = response.GetResponseStream(); long downloadedByte = startPosition; int bufferSize = 512; byte[] btArray = new byte[bufferSize]; int contentSize = readStream.Read(btArray, 0, btArray.Length); while (contentSize > 0) { downloadedByte += contentSize; int percent = (int)(downloadedByte * 100 / totalByte); System.Console.WriteLine("percent=" + percent + "%"); writeStream.Write(btArray, 0, contentSize); contentSize = readStream.Read(btArray, 0, btArray.Length); } readStream.Close(); writeStream.Close(); response.Close(); return; } catch (Exception) { return; } finally { if (readStream != null) { readStream.Close(); } if (writeStream != null) { writeStream.Close(); } } } } }
使用示例:
static void Main(string[] args) { // Ftp下载测试,无用户身份测试 FtpDlder fd = new FtpDlder(); fd.download("ftp://192.168.0.109/jump.jpg", "c:\\asd\\jump.jpg"); }
以上代码参考了 http://blog.csdn.net/jiankunking/article/details/50017009 的代码,在此向原作者表示感谢。
本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/xiandedanteng/p/7090204.html,如需转载请自行联系原作者