如何使用FtpWebRequest恢复损坏的FTP下载

时间:2018-04-20 16:14:10

标签: c# ftp ftpwebrequest ftpwebresponse

我们的系统工作的一些文件很大(> 1GB),所以我需要从破损的FTP下载中恢复。

如果我正在寻找FtpWebResponse流,我会收到一条错误消息,说该流不支持此功能。 有什么方法可以使用普通的FtpWebResponse .net类来实现这个目的吗?

1 个答案:

答案 0 :(得分:0)

发现可以使用ContentOffset

FtpWebRequest属性完成搜索

这是一个有效的例子:

public void deltaFtpTest()
{
    byte[] dl(string url, int offset, int limit)
    {
        using (MemoryStream fs = new MemoryStream())
        {

            FtpWebRequest oFTP = (FtpWebRequest)FtpWebRequest.Create(url);

            oFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            oFTP.UseBinary = true;
            oFTP.UsePassive = true;
            oFTP.Credentials = new NetworkCredential(@"...", "...");

            int size = 0;

            oFTP.ContentOffset = offset;
            using (FtpWebResponse response = (FtpWebResponse)oFTP.GetResponse())
            {
                Stream responseStream = response.GetResponseStream();
                byte[] buffer = new byte[2048];
                int read = 0;

                while (limit > 0)
                {
                    read = responseStream.Read(buffer, 0, buffer.Length);

                    if (read > limit) read = limit; //if excedes limit, truncate

                    fs.Write(buffer, 0, read);
                    size += read;
                    limit -= read;
                }

                responseStream.Close();
                response.Close();

                return fs.ToArray();
            }
        }
    }
    var f = new StreamWriter(@"D:\temp\out.txt");
    var bf = new BinaryWriter(f.BaseStream);
    {
        //getting the first 10 bytes in one session
        bf.Write(dl("ftp://myserver/tmp/t1.txt", 0, 10));

        //getting the rest of the bytes. The file as 60 bytes.
        bf.Write(dl("ftp://myserver/tmp/t1.txt", 10, 50));
        bf.Close();
    }

}