28 Feb

Download files from an FTP directory in .NET

FTP is already a very old technology. The original specification for the File Transfer Protocol was written by Abhay Bhushan and published as RFC 114 on 16 April 1971, which makes it over 45 years old!
Unfortunately when you come in contact with some older software FTP is quite often used as an easy way to store files on the web. Nowadays you’re far better of using Microsoft Azure Blob Storage.
But if you’re feeling nostalgic or if you ever feel the need to download some files from an FTP, this piece of code might help you out.

The Code

I decided to get all files from a directory in two steps.
First I’m going to get all the filenames from a directory. The second step will be to download that file.
I created a console app which will list all the files and it’s content in a string. Of course you will need to change this to fit your needs, but it gives you an idea on how it works.



Step 0: Variables

First we’re going to start of with the essentials for an FTP connection and declare our needed variables.
Our path, login and password.

private const string _ftpPath = "path";
private const string _login = "login";
private const string _password = "password";

 

Step 1: Getting all files from a directory

This piece if pretty straightforward, as is the rest of the code.
I create a WebRequest with a method to show me the directory. After that I just read every line from the stream and filter out what I don’t need.

private static List<string> GetFtpData()
{
    var request = WebRequest.Create(_ftpPath);
    request.Method = WebRequestMethods.Ftp.ListDirectory;
    request.Credentials = new NetworkCredential(_login, _password);

    var files = new List<string>();

    using (var response = request.GetResponse())
    {
        using (var stream = response.GetResponseStream())
        {
            using (var reader = new StreamReader(stream, true))
            {
                while (!reader.EndOfStream)
                {
                    var file = reader.ReadLine();
                    //Make sure you only get the filename and not the whole path.
                    file = file.Substring(file.LastIndexOf('/') + 1);
                    //The root folder will also be added, this can of course be ignored.
                    if (!file.StartsWith("."))
                        files.Add(file);
                }
            }
        }
    }

    return files;
}

 

Step 2: Download the data

I’m using a simple WebClient class to download the data.
According to your needs you could download the data as string, file,… In my case I download it as a byte array. This can be converted into whatever you need.

private static byte[] DownloadData(string path)
{
    var request = new WebClient();
    request.Credentials = new NetworkCredential(_login, _password);

    //This will download the file as byte array. Easy for you to convert it to any type.
    return request.DownloadData(path);
}

Result

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace FtpDownload
{
    class Program
    {
        private const string _ftpPath = "path";
        private const string _login = "login";
        private const string _password = "password";

        static void Main(string[] args)
        {
            var fileNames = GetFtpData();

            Console.WriteLine("==Files==");
            var stringData = new List<string>();
            foreach (var filename in fileNames)
            {
                Console.WriteLine(filename);
                var data = DownloadData($"{_ftpPath}/{filename}");
                stringData.Add(Encoding.UTF8.GetString(data));
            }

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("==Data==");
            foreach (var data in stringData)
                Console.WriteLine(data + Environment.NewLine);

            Console.ReadKey();
        }

        private static byte[] DownloadData(string path)
        {
            var request = new WebClient();
            request.Credentials = new NetworkCredential(_login, _password);

            //This will download the file as byte array. Easy for you to convert it to any type.
            return request.DownloadData(path);
        }

        private static List<string> GetFtpData()
        {
            var request = WebRequest.Create(_ftpPath);
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(_login, _password);

            var files = new List<string>();

            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream, true))
                    {
                        while (!reader.EndOfStream)
                        {
                            var file = reader.ReadLine();
                            //Make sure you only get the filename and not the whole path.
                            file = file.Substring(file.LastIndexOf('/') + 1);
                            //The root folder will also be added, this can of course be ignored.
                            if (!file.StartsWith("."))
                                files.Add(file);
                        }
                    }
                }
            }

            return files;
        }
    }
}


So now you’re ready to download all those files you got stored on your FTP-server.
Let me know if you would have any comments or questions by filling in the form below.

Leave a Reply

Your email address will not be published. Required fields are marked *