Download/Upload files using FTP in C#

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest

 

 

 

 

What is FTP? 

FTP(File transfer protocol)  is a client-server protocol that relies on two communications channels between client and server: a command channel for controlling the conversation and a data channel for transmitting file content. Clients initiate conversations with servers by requesting to download a file. Using FTP, a client can upload, download, delete, rename, move and copy files on a server. A user typically needs to log on to the FTP server, although some servers make some or all of their content available without login, also known as anonymous FTP. FTP server can access by CMD in the windows environment. FileZilla is an open source freely available tool for both FTP server and client.

Ftp Service class for FTP operations

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace betechnical.FTP
{
    ///

    ///
    public class FtpService : IDisposable
    {
        #region Member declaration

        private readonly Queue<string> _downloadlist = new Queue<string>();
        private readonly NetworkCredential _networkCredential;
        private readonly object _sync = new object();
        private readonly FtpUserInfoVo _ftpUserInfo;

        #endregion

        ///

        ///     Constructor with FTP Credential
        ///
        ///
        public FtpService(FtpUserInfoVo ftpUserInfo)
        {
            _ftpUserInfo = ftpUserInfo;
            _networkCredential = new NetworkCredential(ftpUserInfo.UserName, ftpUserInfo.Password);

        }

        ///

        ///
        public string HostUrl
        {
            get { return string.Format("ftp://{0}", _ftpUserInfo.Host); }
        }

        ///

        /// 
        ///
        /// 
        public IList<string> ListDirectories(string directory)
        {
            var url = string.IsNullOrEmpty(directory) ? HostUrl : HostUrl + "/" + directory;
            var dirlist = new List<string>();
            var ftprequest = WebRequest.Create(url);
            ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
            ftprequest.Credentials = _networkCredential;
            ftprequest.Timeout = 1200000;
            using (var ftpresponse = (FtpWebResponse) ftprequest.GetResponse())
            {
                var responcestream = ftpresponse.GetResponseStream();
                if (responcestream == null) return dirlist;
                using (var streamreader = new StreamReader(responcestream))
                {
                    while (!streamreader.EndOfStream)
                    {
                        var file = streamreader.ReadLine();
                        if (file != null)
                        {
                            dirlist.Add(file);
                        }
                    }
                }
            }
            return dirlist;
        }

        ///

        /// 
        ///
        ///
        ///
        public void UploadFile(string directory, string filepath)
        {
            try
            {
                var fs = new FileStream(filepath,FileMode.Open);
                var filename = Path.GetFileName(filepath);
                var url = string.IsNullOrEmpty(directory) ? HostUrl : HostUrl + "/" + directory + "/" + filename;
                var ftprequest = WebRequest.Create(url);
                ftprequest.Method = WebRequestMethods.Ftp.UploadFile;
                ftprequest.Credentials = _networkCredential;
                ftprequest.Timeout = 1200000;
                using (var ftpstream = ftprequest.GetRequestStream())
                {
                    var buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    fs.Close();
                    ftpstream.Write(buffer, 0, buffer.Length);
                    ftpstream.Close();
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(string.Format("Ftp Host : {0} with username : {1}",
                    _ftpUserInfo.Host, _networkCredential.UserName));
                Console.WriteLine(ex);
            }
        }

        ///

        ///
        public void DownloadFiles(string directory)
        {
            try
            {
                var url = string.IsNullOrEmpty(directory) ? HostUrl : HostUrl + "/" + directory;
                var ftprequest = WebRequest.Create(url);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftprequest.Credentials = _networkCredential;
                ftprequest.Timeout = 1200000;
                using (var ftpresponse = (FtpWebResponse) ftprequest.GetResponse())
                {
                    var responcestream = ftpresponse.GetResponseStream();
                  
                    if (responcestream != null)
                    {
                        using (var streamreader = new StreamReader(responcestream))
                        {
                            while (!streamreader.EndOfStream)
                            {
                                var file = streamreader.ReadLine();
                                if (file == null) continue;
                                var filename = file.Split('/').Last();
                                if (!file.Contains("."))
                                {
                                    DownloadFiles(directory + "/" + filename);
                                }
                                file = url + "/" + filename;
                                _downloadlist.Enqueue(file);
                            }
                        }
                    }
                }
                if (_downloadlist.Count > 0 && _downloadlist.ElementAt(0).Equals("access.log"))
                {
                    _downloadlist.Dequeue();
                }
                StartDownloading();
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Connecting to Ftp Host : {0} with username : {1}",
                    _ftpUserInfo.Host, _networkCredential.UserName));
                Console.WriteLine(ex);
            }
        }

        ///

        ///
        private async void StartDownloading()
        {
            while (_downloadlist.Count > 0)
            {
                try
                {
                    #region File Path Configuration

                    var sourcefilepath = _downloadlist.Dequeue();
                    var destinationfilepath = string.Format("{0}\\{1}", _ftpUserInfo.DownloadPath,
                        Path.GetFileName(sourcefilepath));
                    #endregion
                    var request = WebRequest.Create(sourcefilepath) as FtpWebRequest;
                    if (request == null) continue;
                    request.UseBinary = true;
                    request.Timeout = 1200000;
                    request.ReadWriteTimeout = 1200000;
                    request.UsePassive = true;
                    request.KeepAlive = false;
                    request.EnableSsl = false;
                    request.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5";
                    request.Credentials = _networkCredential;
                    request.Method = WebRequestMethods.Ftp.DownloadFile;
                    using (var response = (FtpWebResponse) await request.GetResponseAsync())
                    {
                        lock (_sync)
                        {
                            Console.WriteLine("Downloading file " + sourcefilepath);
                            if (response.ContentLength <= 0) continue;
                            using (var file = File.Create(destinationfilepath))
                            {
                                var responseStream = response.GetResponseStream();
                                if (responseStream == null) continue;
                                responseStream.CopyTo(file);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Ftp Host : {0}", _ftpUserInfo.Host));
                   Console.WriteLine(ex);
                }
            }
        }

      

        ///

        ///
        ///
        /// 
        protected virtual async Task FtpFileCreationTime(Uri url)
        {
            try
            {
                var creationtime = WebRequest.Create(url) as FtpWebRequest;
                if (creationtime != null)
                {
                    creationtime.UsePassive = false;
                    creationtime.UseBinary = true;
                    creationtime.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"; 
                    creationtime.Credentials = _networkCredential;
                    creationtime.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                    using (var filecreationtime = await creationtime.GetResponseAsync() as FtpWebResponse)
                    {
                        return filecreationtime != null ? filecreationtime.LastModified : DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return DateTime.Now;
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}

FtpInfo class for passing the credential

namespace betechnical.FTP
{
    ///

    /// 
    ///
    public class FtpUserInfoVo
    {
        public string Host { get; set; }
        public string DownloadPath { get; set; }
        public string Password { get; set; }
        public string Port { get; set; }
        public string UserName { get; set; }
    }
}
Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on whatsapp
Share on email
Author Bio

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recommended for you
Connect With Us
Stay Connected

Subscribe to our newsletter today to receive updates on latest tech news, tutorials SEO tips many more.

Latest Articles
18518157_223940698108354_7866972342651071979_o
Apps

5 Best Apps for self-development

We live in a world of high dynamicity, progress, and constant change. But in most times it has been observed that we are not that welcoming when it comes to changing ourselves or changing anything around us. We try to repel change as long as possible.

Free hub for guest blogging nerds and newbie writers

  • Submit Guest Post
  • Share your Knowledge
  • Build your Backlinks
  • Advertise your products
  • Make money by writing
Subscribe to our newsletter today to receive updates on latest tech news, tutorials SEO tips many more.