In almost all ASP.NET web application, we have to write
a code to download file from FTP server.
Here is simple and full code to download file via FTP.
It uses FTP web request and response stream for
connecting and downloading file from FTP server by using credentials.
public static bool FTPDownloadFile(string sAddress, string sUserName, string sPassword, bool isUsePassive, string sDownloadFileName, string sServerFileName)
{
Stream ftpStream = null;
int bufferSize = 2048;
bool bReturnValue = false;
FtpWebRequest ftpRequest =
(FtpWebRequest)FtpWebRequest.Create(sAddress + @"/" + sServerFileName);
ftpRequest.Method =
WebRequestMethods.Ftp.DownloadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
ftpRequest.EnableSsl = isSSL;
ftpRequest.Credentials = new NetworkCredential(sUserName,
sPassword);
ftpRequest.UsePassive = isUsePassive;
FtpWebResponse ftpResponse =
(FtpWebResponse)ftpRequest.GetResponse();
ftpStream =
ftpResponse.GetResponseStream();
FileStream localFileStream = new FileStream(sDownloadFileName, FileMode.Create);
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer,
0, bytesRead);
bytesRead =
ftpStream.Read(byteBuffer, 0, bufferSize);
}
bReturnValue = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (localFileStream != null)
{
localFileStream.Close();
}
if (ftpStream != null)
{
ftpStream.Close();
}
if (ftpResponse != null)
{
ftpResponse.Close();
}
ftpRequest = null;
}
return bReturnValue;
}
Please leave your comments or share this code if it’s
useful for you.