I wrote this C# code but how can I get the filesize of the file I want to download from my FTP server and begin a download?
At the moment, my code fails to calculate the percentage and it is completely incorrect because I cannot get the filesize of the file I want to download.
If I change request2.Method = WebRequestMethods.Ftp.DownloadFile;
to request2.Method = WebRequestMethods.Ftp.GetFileSize;
I then manage to pull the filesize, but downloading stops working. Is there a way to do both?
FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create("ftp://username@127.0.0.1/myfile.zip");
request2.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response2 = (FtpWebResponse)request2.GetResponse();
responseStream = response2.GetResponseStream();
using (StreamReader reader = new StreamReader(responseStream))
{
//Console.WriteLine(reader.ReadToEnd());
// get the current date as DD-MMM-YYYY
DateTime dt = System.DateTime.Now;
string fdate = String.Format("{0:dd_MMM_yyyy}", dt);
string fdate2 = fdate.ToUpper(); // convert to uppercase
int length = (int)request2.GetResponse().ContentLength;
//double length = response2.ContentLength;
long downloaded = 0;
long result = 0;
int bufferSize = 32 * 1024;
byte[] buffer = new byte[bufferSize];
using (FileStream writer = new FileStream("MYFILE" + fdate2 + ".ZIP", FileMode.Create))
{
Console.Write("\n\rMYFILE.ZIP = {0:N0} Bytes ({1:N0} Megabytes).\n", length, length/1024); // format the filesize with a comma
Console.Write("NOTE: Press [CTRL+C] to cancel and terminate this program at anytime...\n\n");
int readCount = responseStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
writer.Write(buffer, 0, readCount); // byte
readCount = responseStream.Read(buffer, 0, bufferSize);
downloaded += readCount; // increment
double dProgress = ((double)downloaded / length) * 100.0;
result = Convert.ToInt32(dProgress);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("\r DOWNLOADING 1/1... {0}%", result);
}
}
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("\n\nDownload Complete! STATUS: {0}", response2.StatusDescription);
reader.Close();
}
Thanks.