I'm trying to download a file using FtpWebRequest
.
private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{
int bytesRead = 0;
byte[] buffer = new byte[1024];
FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stream reader = request.GetResponse().GetResponseStream();
BinaryWriter writer = new BinaryWriter(File.Open(localDestinationFilePath, FileMode.CreateNew));
while (true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
writer.Write(buffer, 0, bytesRead);
}
}
It uses this CreateFtpWebRequest
method I created:
private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive = false)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirectoryPath));
//Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
request.Proxy = null;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = keepAlive;
request.Credentials = new NetworkCredential(userName, password);
return request;
}
It downloads it. But the information is always corrupted. Anyone know what's going on?
Just figured it out:
Had to use a FileStream instead.
The most trivial way to download a file from an FTP server using .NET framework is using
WebClient.DownloadFile
method:Use
FtpWebRequest
class, if you need a greater control only, thatWebClient
class does not offer (like TLS/SSL encryption, progress monitoring etc). An easy way, is to just copy an FTP response stream toFileStream
usingStream.CopyTo
method:Only, if you need to monitor a download progress, you have to copy the contents by chunks yourself:
For GUI progress (WinForms
ProgressBar
), see:FtpWebRequest FTP download with ProgressBar
If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.