c# FTP文件下载超时

本文关键字:超时 文件下载 FTP | 更新日期: 2023-09-27 18:07:13

我正在从FTP服务器下载一个文件。当它到达最后一个字节时,它会冻结并超时。我必须将超时设置为-1,这样它就不会超时,但最后一个字节永远不会完成。

任何想法?

      FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxx" + "/" + fileDownload);
            request.Credentials = new NetworkCredential("xxx", "xxx");
            request.UseBinary = true;
            request.KeepAlive = true;
            request.Timeout = -1;
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            FileStream writer = File.Create(@"c:'temp'" + Path.GetFileNameWithoutExtension(fileDownload) + ".csv");

            long length = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[2048];
           // readCount = responseStream.Read(buffer, 0, bufferSize);
            while (responseStream.CanRead)
            {
                readCount = responseStream.Read(buffer, 0, bufferSize);
                writer.Write(buffer, 0, readCount);
            }     
            responseStream.Close();
            response.Close();
            writer.Close();

c# FTP文件下载超时

CanRead并不像你想象的那样。它只是指示是否实际上可以从读取流。而不是是否有剩余的字节。而是像这样重写你的循环:

for (int readCount; (readCount = responseStream.Read(buffer, 0, bufferSize)) > 0;) 
{ 
    writer.Write(buffer, 0, readCount); 
}