如何在C#app中解决FTP超时问题

5 c# ftp

我正在使用以下C#代码从远程服务提供商FTP一个~40MB的CSV文件.大约50%的时间,下载挂起并最终超时.在我的应用程序日志中,我得到一行:

> Unable to read data from the transport
> connection: A connection attempt
> failed because the connected party did
> not properly respond after a period of
> time, or established connection failed
> because connected host has failed to
> respond.
Run Code Online (Sandbox Code Playgroud)

当我使用像LeechFTP这样的图形客户端以交互方式下载文件时,下载几乎从不挂起,并在大约45秒内完成.我有一段时间了解出了什么问题.

任何人都可以建议我如何使用此代码来更深入地了解正在发生的事情,或者更好地下载此文件的方法?我应该增加缓冲区大小吗?多少钱?避免缓冲写入磁盘并尝试吞下内存中的整个文件?任何建议赞赏!

...

private void CreateDownloadFile()
    {
        _OutputFile = new FileStream(_SourceFile, FileMode.Create);
    }
public string FTPDownloadFile()
    {
        this.CreateDownloadFile();

        myReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(this.DownloadURI));
        myReq.Method = WebRequestMethods.Ftp.DownloadFile;
        myReq.UseBinary = true;
        myReq.Credentials = new NetworkCredential(_ID, _Password);

        FtpWebResponse myResp = (FtpWebResponse)myReq.GetResponse();
        Stream ftpStream = myResp.GetResponseStream();

        int bufferSize = 2048;
        int readCount;
        byte[] buffer = new byte[bufferSize];
        int bytesRead = 0;
        readCount = ftpStream.Read(buffer, 0, bufferSize);

        while (readCount > 0)
        {
            _OutputFile.Write( buffer, 0, readCount );
            readCount = ftpStream.Read( buffer, 0, bufferSize );

            Console.Write( '.' );    // show progress on the console
            bytesRead += readCount;
        }
        Console.WriteLine();
        logger.logActivity( "    FTP received " + String.Format( "{0:0,0}", bytesRead ) + " bytes" );

        ftpStream.Close();
        _OutputFile.Close();
        myResp.Close();
        return this.GetFTPStatus();
    }

    public string GetFTPStatus()
    {
        return ((FtpWebResponse)myReq.GetResponse()).StatusDescription;
    }
Run Code Online (Sandbox Code Playgroud)

gil*_*nba 0

我没有在代码层面处理过 FTP,但 FTP 支持断点续传。也许你可以让它在超时时自动尝试恢复上传