0

我正在从我的 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();
4

1 回答 1

0

CanRead不做你认为它做的事。它只是表示实际上是否可以读取流不是是否还有剩余字节。而是像这样重写你的循环:

for (int readCount; (readCount = responseStream.Read(buffer, 0, bufferSize)) > 0;) 
{ 
    writer.Write(buffer, 0, readCount); 
}
于 2013-04-03T00:58:30.377 回答