Welcome

Hello, Welcome to my blog. If you like feel free to refer others

Wednesday, 8 April 2015

Download file from FTP

Add 2 reference in your class:
using System.Net;
using System.IO;

Then copy below mentioned method
public static bool DownloadFile(string userId, string password, string ftpServerPath, string fileName, string localPath)
        {
            FtpWebRequest reqFTP;
            bool status = false;
            try
            {
                String downloadUrl = String.Format("{0}{1}/{2}", @"ftp:", ftpServerPath,fileName);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(downloadUrl));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, password);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                using (WebResponse response = reqFTP.GetResponse())
                {
                    using (Stream downloadStream = response.GetResponseStream())//;//read the download file from his stream
                    {
                        using (FileStream fs = File.Create(localPath + @"\" + fileName))
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = downloadStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            }
                            while (read != 0);
                            status = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                status = false;
            }
            finally
            {               
                reqFTP = null;
            }
            return status;
        }

Above mentioned method will download the desired file from FTP server to your local file system.

Happy learning......

No comments:

Post a Comment