使用ftp协议下载大文件

时间:2015-09-11 15:01:52

标签: c# ftp

我知道这可能不是第一次,这是被问到的。 但我无法找到问题的解决方案..

  private void bgftpdownload_DoWork(object sender, DoWorkEventArgs e)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl + "/" + clientlabel.Text + "/data.7z");
        request.Credentials = new NetworkCredential(ftpuser, ftppass);
        request.Method = WebRequestMethods.Ftp.GetFileSize;
        request.Proxy = null;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        long fileSize = response.ContentLength;

        request = (FtpWebRequest)WebRequest.Create(ftpurl + "/" + clientlabel.Text + "/data.7z");
        request.Credentials = new NetworkCredential(ftpuser, ftppass);
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        using (FtpWebResponse responseFileDownload = (FtpWebResponse)request.GetResponse())
        using (Stream responseStream = responseFileDownload.GetResponseStream())
        using (FileStream writeStream = new FileStream(LocationFile, FileMode.Create))
        {

            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);
            int bytes = 0;

            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
                bytes += bytesRead;
                int totalSize = (int)(fileSize / 1048576);
                bgftpdownload.ReportProgress((bytes / 1048576) * 100 / totalSize, totalSize);
            }
        }
    }
    private void bgftpdownload_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
            progresslabel.Text = e.ProgressPercentage * (int)e.UserState / 100 + " Mb / " + e.UserState + " Mb";
            progressBar1.Value = e.ProgressPercentage;
    }

我有这个代码,它工作得很好..直到它在ftp服务器上点击一个2 GB的文件

我可以在其他论坛上看到,(int)的值限制是= 2147483591 所以问题是因为我的字节高于限制(2147483591)

System.Windows.Forms.dll中发生了'System.ArgumentOutOfRangeException'类型的异常,但未在用户代码中处理

其他信息:Værdien'-45'er ugyldig for'Value'。 '价值'skalværemellem'最小'og'最大'。

我该怎么做才能解决这个问题?

2 个答案:

答案 0 :(得分:0)

您的进度条触发失败,尝试将其设置为-45无效。

int totalSize = (int)(fileSize / 1048576);
bgftpdownload.ReportProgress((bytes / 1048576) * 100 / totalSize, totalSize);

你的totalSize会出现溢出,这会导致负%,导致你看到的错误。

......至少我认为那是错的。

答案 1 :(得分:0)

long bytes = 0;

bgftpdownload.ReportProgress((int)(bytes / 1048576) * 100 / totalSize, totalSize);
是解决方案,我把(int)放在ReportProgress的错误位置。