2012-01-18 120 views
0

我想下载一个目录,在C#应用程序中使用FTP。我基本上需要采取一个远程目录,并将其移动到其本地目录。C# - 下载目录 - FTP

这是我目前使用的功能,以及日志输出和错误是什么。我引用的样本是获取文件,并可能不是目录:

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"); 
     } 
    } 

调试:

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输出:

The requested URI is invalid for this FTP command. 
+0

目标目录是否存在于FTP服务器上?您正在使用的用户是否拥有正确的权限? – Oded 2012-01-18 16:47:38

+0

@Oded:确实如此,用户确实如此。我以前列出目录并创建目录的CheckedListBox作为选项。我也可以使用FileZilla手动获取数据。 – Josh 2012-01-18 16:48:47

回答

3

上GETDIR末端的斜杠表示一个目录 - 你可以使用mget并传递一个类似于“/ *”结尾的路径吗?

+0

我不确定你的意思是'mget',但是在请求的末尾添加*并不能解决它。 – Josh 2012-01-18 16:51:32

+1

对不起,我在考虑命令行FTP,其中mget是获取多个文件的命令。它看起来像WebRequestMethods.Ftp中没有相同的。如何使用ListDirectory方法获取列表然后循环? – upsidedowncreature 2012-01-18 16:58:49

+0

我已经接受了你的答案,因为'mget'给了我列出dir内容的想法,并且一次一个地循环它们以获取它们。 – Josh 2012-01-18 17:06:42