Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles CA and Austin TX. Follow galratner on Twitter Google
How to upload and download files using FTP in C#

Here are two useful methods designed to upload and download files from an FTP server using FtpWebRequest.

        /// <summary>

        /// Upload a file using FTP

        /// </summary>

        /// <param name="FTPServer">The server to upload to</param>

        /// <param name="remotePath">The remote path in the server</param>

        /// <param name="fileToUpload">The path to the local uploaded file</param>

        /// <param name="user">User to log onto the FTP server</param>

        /// <param name="password">Password to log onto the FTP server</param>

        /// <returns>The status of the upload</returns>

        public static string Upload(string FTPServer, string remotePath, string fileToUpload, string user, string password)

        {

            try

            {

                //Get FTP web resquest object.

                FtpWebRequest request = FtpWebRequest.Create(new Uri(@"ftp://" + FTPServer + @"/" + remotePath + @"/" + Path.GetFileName(fileToUpload))) as FtpWebRequest;

                request.UseBinary = true;

                request.KeepAlive = false;

                request.Method = WebRequestMethods.Ftp.UploadFile;

                if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(password))

                    request.Credentials = new NetworkCredential(user, password);

 

                //Get physical file

                FileInfo fi = new FileInfo(fileToUpload);

                Byte[] contents = new Byte[fi.Length];

 

                //Read file

                FileStream fs = fi.OpenRead();

                fs.Read(contents, 0, Convert.ToInt32(fi.Length));

                fs.Close();

 

                //Write file contents to FTP server

                Stream rs = request.GetRequestStream();

                rs.Write(contents, 0, Convert.ToInt32(fi.Length));

                rs.Close();

 

                FtpWebResponse response = request.GetResponse() as FtpWebResponse;

                string statusDescription = response.StatusDescription;

                response.Close();

                return statusDescription;

            }

            catch (Exception e)

            {

                throw new Exception("Error uploading to URL " + "ftp://" + FTPServer + @"/" + remotePath + @"/" + Path.GetFileName(fileToUpload), e);

            }

        }

 

        /// <summary>

        /// Download a file using FTP

        /// </summary>

        /// <param name="FTPServer">The server to download from</param>

        /// <param name="remotePath">The remote path in the server</param>

        /// <param name="fileNameToDownload">The remote file name</param>

        /// <param name="saveToLocalPath">The path to the folder to download to</param>

        /// <param name="user">User to log onto the FTP server</param>

        /// <param name="password">Password to log onto the FTP server</param>

        /// <returns>The status of the download</returns>

        public static string Download(string FTPServer, string remotePath, string fileNameToDownload, string saveToLocalPath, string user, string password)

        {

            try

            {

                //Get FTP web resquest object.

                FtpWebRequest request = FtpWebRequest.Create(new Uri(@"ftp://" + FTPServer + @"/" + remotePath + @"/" + fileNameToDownload)) as FtpWebRequest;

                request.UseBinary = true;

                request.KeepAlive = false;

                request.Method = WebRequestMethods.Ftp.DownloadFile;

                if(!string.IsNullOrEmpty(user)&&!string.IsNullOrEmpty(password))

                    request.Credentials = new NetworkCredential(user, password);

 

                FtpWebResponse response = request.GetResponse() as FtpWebResponse;

                Stream responseStream = response.GetResponseStream();

                FileStream outputStream = new FileStream(saveToLocalPath + "\\" + fileNameToDownload, FileMode.Create);

 

                int bufferSize = 1024;

                int readCount;

                byte[] buffer = new byte[bufferSize];

 

                readCount = responseStream.Read(buffer, 0, bufferSize);

                while (readCount > 0)

                {

                    outputStream.Write(buffer, 0, readCount);

                    readCount = responseStream.Read(buffer, 0, bufferSize);

                }

                string statusDescription = response.StatusDescription;

                responseStream.Close();

                outputStream.Close();

                response.Close();

                return statusDescription;

            }

            catch (Exception e)

            {

                throw new Exception("Error downloading from URL " + "ftp://" + FTPServer + @"/" + remotePath + @"/" + fileNameToDownload, e);

            }

        }

 Enjoy!


Posted 27 Nov 2009 8:26 AM by Gal Ratner
Filed under: ,

Powered by Community Server (Non-Commercial Edition), by Telligent Systems