I am trying to download files from ftp server with this code:
using (System.IO.FileStream fileStream = System.IO.File.OpenWrite(filePath))
{
byte[] buffer = new byte[4096];
int bytesRead = responseStream.Read(buffer, 0, 4096);
while (bytesRead > 0)
{
fileStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, 4096);
}
}
The creation of responseStream:
System.IO.Stream responseStream = GetFileAsStream(url, username, password, false);
public static System.IO.Stream GetFileAsStream(string ftpUrl, string username, string password, bool usePassive)
{
System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpUrl);
request.KeepAlive = false;
request.ReadWriteTimeout = 120000;
request.Timeout = -1;
request.UsePassive = usePassive;
request.Credentials = new System.Net.NetworkCredential(username, password);
request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
System.IO.Stream fileResponseStream;
System.Net.FtpWebResponse fileResponse = (System.Net.FtpWebResponse)request.GetResponse();
fileResponseStream = fileResponse.GetResponseStream();
return fileResponseStream;
}
It works fine with smaller files but when a file is bigger (e.g. 150mb) the process hangs. For some reason the program does not understand that it has completed the download and it still tries to read more bytes.
I prefer answers which do not include using external libraries. Thank you