C# Upload whole directory using FTP

cdirectoryftprecursionupload

What I'm trying to do is to upload a website using FTP in C# (C Sharp). So I need to upload all files and folders within a folder, keeping its structure. I'm using this FTP class: http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class for the actual uploading.

I have come to the conclusion that I need to write a recursive method that goes through every sub-directory of the main directory and upload all files and folders in it. This should make an exact copy of my folder to the FTP. Problem is… I have no clue how to write a method like that. I have written recursive methods before but I'm new to the FTP part.

This is what I have so far:

private void recursiveDirectory(string directoryPath)
    {
        string[] filePaths = null;
        string[] subDirectories = null;

        filePaths = Directory.GetFiles(directoryPath, "*.*");
        subDirectories = Directory.GetDirectories(directoryPath);

        if (filePaths != null && subDirectories != null)
        {
            foreach (string directory in subDirectories)
            {
                ftpClient.createDirectory(directory);
            }
            foreach (string file in filePaths)
            {
                ftpClient.upload(Path.GetDirectoryName(directoryPath), file);
            }
        }
    }

But its far from done and I don't know how to continue. I'm sure more than me needs to know this! Thanks in advance 🙂

Ohh and… It would be nice if it reported its progress too 🙂 (I'm using a progress bar)

EDIT:
It might have been unclear… How do I upload a directory including all sub-directories and files with FTP?

Best Answer

Problem Solved! :)

Alright so I managed to write the method myslef. If anyone need it feel free to copy:

private void recursiveDirectory(string dirPath, string uploadPath)
    {
        string[] files = Directory.GetFiles(dirPath, "*.*");
        string[] subDirs = Directory.GetDirectories(dirPath);

        foreach (string file in files)
        {
            ftpClient.upload(uploadPath + "/" + Path.GetFileName(file), file);
        }

        foreach (string subDir in subDirs)
        {
            ftpClient.createDirectory(uploadPath + "/" + Path.GetFileName(subDir));
            recursiveDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir));
        }
    }

It works very well :)