我正从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();
答案 0 :(得分:0)
CanRead
没有按照您的想法行事。它只是表明实际上是否可以从中读取流。不是否有剩余的字节。而是像这样重写你的循环:
for (int readCount; (readCount = responseStream.Read(buffer, 0, bufferSize)) > 0;)
{
writer.Write(buffer, 0, readCount);
}