Josh
Josh

Reputation: 12566

C# - Download Directory - FTP

I'm trying to download a directory, using FTP in a C# application. I basically need to take a remote dir, and move it, and its contents into a local dir.

Here is the function I'm currently using, and what the log output and errors are. The sample I'm referencing is for getting files, and possibly not directories:

    private void Download(string file, string destination)
    {                       
        try
        {
            string getDir = "ftp://" + ftpServerIP + ftpPath + file + "/";
            string putDir = destination + "\\" + file;

            Debug.WriteLine("GET: " + getDir);
            Debug.WriteLine("PUT: " + putDir);

            FtpWebRequest reqFTP;                

            reqFTP = (FtpWebRequest)FtpWebRequest.Create
               (new Uri(getDir));

            reqFTP.Credentials = new NetworkCredential(ftpUserID,
                                                       ftpPassword);
            reqFTP.UseBinary = true;

            reqFTP.KeepAlive = false;                
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                                
            reqFTP.Proxy = null;                 
            reqFTP.UsePassive = false;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream responseStream = response.GetResponseStream();
            FileStream writeStream = new FileStream(putDir, FileMode.Create);                
            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);               
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
            }                
            writeStream.Close();
            response.Close(); 
        }
        catch (WebException wEx)
        {
            MessageBox.Show(wEx.Message, "Download Error");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Download Error");
        }
    }

Debug:

GET: ftp://I.P.ADDR/SOME_DIR.com/members/forms/THE_FOLDER_TO_GET/
PUT: C:\Users\Public\Documents\iMacros\Macros\THE_FOLDER_TO_WRITE
A first chance exception of type 'System.Net.WebException' occurred in System.dll

MessageBox Output:

The requested URI is invalid for this FTP command.

Upvotes: 1

Views: 3543

Answers (1)

upsidedowncreature
upsidedowncreature

Reputation: 627

The slash on the end of the getDir indicates a directory - can you use mget and pass a path like that ends in "/*"?

Upvotes: 3

Related Questions