0

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();
}

example 1

example 2

Thanks.

matead
  • 47
  • 5

1 Answers1

1

To retrieve the file size and download the file using FTP in C#, you can make separate requests to obtain the file size and then perform the download

using System;
using System.IO;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        string ftpUrl = "ftp://username@127.0.0.1/myfile.zip";
        string localFilePath = "MYFILE.zip";

        long fileSize = GetFileSize(ftpUrl);
        if (fileSize > 0)
        {
            DownloadFile(ftpUrl, localFilePath, fileSize);
            Console.WriteLine("Download Complete!");
        }
        else
        {
            Console.WriteLine("Failed to retrieve file size.");
        }
    }

    static long GetFileSize(string ftpUrl)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
        request.Method = WebRequestMethods.Ftp.GetFileSize;

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            return response.ContentLength;
        }
    }

    static void DownloadFile(string ftpUrl, string localFilePath, long fileSize)
    {
        using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create))
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            {
                byte[] buffer = new byte[32 * 1024];
                int bytesRead;
                long totalBytesRead = 0;

                while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fileStream.Write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;

                    double progress = (double)totalBytesRead / fileSize * 100.0;
                    Console.WriteLine($"Downloaded: {progress:F2}%");
                }
            }
        }
    }
}

In this updated code, the GetFileSize method sends a WebRequest with the method GetFileSize to retrieve the size of the file. Then, the DownloadFile method performs the actual file download using the DownloadFile method of FtpWebRequest. The progress calculation has also been adjusted to display the correct percentage based on the file size.

CherryQuery
  • 428
  • 1
  • 11