【发布时间】:2009-04-24 18:55:24
【问题描述】:
我正在使用以下 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.
当我使用 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;
}
【问题讨论】: