Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file using ftp in c# [duplicate]

Tags:

c#

ftp

As a junior developper, I should find a solution to download a file using ftp and I have this code.
It works but sometimes, I can not open the downloaded file.

public static bool DownloadDocument(string ftpPath, string downloadPath) {
  bool retVal = false;
  try {
    Uri serverUri = new Uri(ftpPath);
    if (serverUri.Scheme != Uri.UriSchemeFtp) {
        return false;
    }
    FtpWebRequest reqFTP;
    reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);
    reqFTP.Credentials = new NetworkCredential(Tools.FtpUserName, Tools.FtpPassword);
    reqFTP.KeepAlive = false;
    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
    reqFTP.UseBinary = true;
    reqFTP.Proxy = null;
    reqFTP.UsePassive = false;

    using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse()) {
      using (Stream responseStream = response.GetResponseStream()) {
        using (FileStream writeStream = new FileStream(downloadPath, FileMode.Create)) {
          int Length = 1024 * 1024 * 30;
          Byte[] buffer = new Byte[Length];
          responseStream.Read(buffer, 0, Length);
        }
      }
    }
    retVal = true;
  }
  catch (Exception ex) {
    //Error logging to add
  }

  return retVal;
}

Any ideas please!

like image 910
Tony_Clark Avatar asked Sep 15 '25 00:09

Tony_Clark


1 Answers

Why don't you use it?. WebClient implemented by Microsoft for a download from FTP.

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential("log", "pass");
    client.DownloadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

}
like image 56
Antoine V Avatar answered Sep 16 '25 18:09

Antoine V