C# – Simple FTP Service

Here is a quick snippet for FTP services using standard C#/.NET libraries.

The task is to download a file from a remote FTP server using standard C#/.NET libraries.

I assume that you have the FTP server details (Host, Username, Password).

The code is pretty straight forward, I have given comments where required.

/* FTPService.cs */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MyProject
{
    public class FTPService
    {
        //request object
        private FtpWebRequest ftpRequest = null;
        //response object
        private FtpWebResponse ftpResponse = null;
        //stream object to read
        private Stream ftpStream = null;
        
        //Host address like ftp://something.net/
        public string Host { get; set; }
        //ftp username
        public string Username { get; set; }
        //ftp password
        public string Password { get; set; }
        //local directory where the file will be downloaded.
        public string LocaDirectory { get; set; }

       

       
        public void GetFile(string fileName)
        {
            try
            {
		//create FTP request
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", Host, fileName));
		//add authentication details                
                ftpRequest.Credentials = new NetworkCredential(Username, Password);
                //set ftp options
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                // Get response from ftp server
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpStream = ftpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(ftpStream);
                //download the file and copy it to local directory
                using (var file = File.Create(LocaDirectory + fileName))
                {
                    ftpStream.CopyTo(file);
                }


            }
            catch (Exception ex)
            {
            	LogError(ex);
            }

            finally
            {
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
            }
            
        }

        

       
    }
}

Then you can call this service in your project using the following snippet

        
        private static void DownlaodFTPFile()
        {
            FTPService service = new FTPService();

            service.Host = ConfigurationManager.AppSettings["Host"];
            service.Username = ConfigurationManager.AppSettings["Username"];
            service.Password = ConfigurationManager.AppSettings["Password"];
            service.LocaDirectory = ConfigurationManager.AppSettings["LocalDirectory"];

            string fileName = "DownloadFile.txt";

            service.GetFile(fileName);
        }

Always best practise to use web.config/app.config for hard-coded details, it takes time but it in long run it eventually pays off

Thanks!

Advertisements

One thought on “C# – Simple FTP Service

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s