Tuesday, February 24, 2009

How to download file from FTP server using C#

Add below namespaces,
using System.Net;
using System.IO;
using System.Text;

Create a button and add the below code under button click
//fileName = Name of the file to be downloaded from FTP server.
        string fileName = "test.txt";

        //filePath = The full path where the file is to be created. Here i put local system path.
        string filePath = "C:\\FTP";
        
        string ftpServerIP = "<IP Address>";
        string ftpUserID = "<User ID>";
        string ftpPassword = "<Password>";
        FtpWebRequest reqFTP;
        try
        {
            FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();
        }
        catch (Exception ex)
        {
           string errMsg= (ex.Message);
        }

Execute the code and see the C:\FTP folder for the file….