Below is a method to download content from an FTP, but if I just let the program run, it fails. If I step slowly through the code, it works. If I just let it run on its own, it only downloads 5kb of the file, and then moves on. It doesn't throw an exception, it just downloads the 5kb and then quits, moving onto the next item.
private static void DownloadFtpFile(string sourceFileLocation)
{
try
{
int bufferSize = 1024 * 300;
int totalBytes = 0;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceFileLocation);
long contentLength = webRequest.GetResponse().ContentLength;
Console.WriteLine(totalBytes);
using (WebResponse webResponse = webRequest.GetResponse())
using (Stream reader = webResponse.GetResponseStream())
using (BinaryWriter fileWriter = new BinaryWriter(File.Create(Application.StartupPath + "\\" + "tempFldr" + "\\" + "tempFile")))
{
int bytesRead = 0;
byte[] buffer = new byte[bufferSize];
do
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
totalBytes += bytesRead;
fileWriter.Write(buffer, 0, bytesRead);
Console.WriteLine("BytesRead: " + bytesRead + " -- TotalBytes: " + totalBytes);
} while (bytesRead > 0);
}
}
catch (WebException ex)
{
String status = ((HttpWebResponse)ex.Response).StatusDescription;
Console.WriteLine(status);
}
}
To start, try switching from HttpWebRequest to FtpWebRequest. Not sure if that will make a huge difference, but if you're getting stuff from an FTP it may.
I feel like you might change from using a do-while to a while with something like this:
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
fileWrite.Write(chunk, 0, bytesRead);
totalBytes += bytesRead;
Console.WriteLine("BytesRead: " + bytesRead + " -- TotalBytes: " + totalBytes);
}
Something else you may consider, maybe just download the file to a stream, then save it to the file after you've already closed the FTP connection.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments