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!
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With