【问题标题】:C# - Download Directory - FTPC# - 下载目录 - FTP
【发布时间】:2012-02-13 09:31:01
【问题描述】:

我正在尝试在 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

消息框输出:

The requested URI is invalid for this FTP command.

【问题讨论】:

  • FTP服务器上是否存在目的目录?您使用的用户是否具有正确的权限?
  • @Oded:确实如此,用户也如此。我之前列出了目录并创建了一个 CheckedListBox 目录作为选项。我也可以使用 FileZilla 手动获取数据。

标签: c# .net ftp


【解决方案1】:

getDir 末尾的斜线表示一个目录 - 您可以使用 mget 并传递以“/*”结尾的路径吗?

【讨论】:

  • 我不确定您所说的 mget 究竟是什么意思,但在请求末尾添加 * 并不能解决问题。
  • 对不起,我在考虑命令行 FTP,其中 mget 是获取多个文件的命令。看起来 WebRequestMethods.Ftp 中没有等价物。如何使用 ListDirectory 方法获取列表然后循环呢?
  • 我接受了你的回答,因为mget 给了我列出目录内容的想法,然后一次循环获取它们。
  • @Josh - 这真的是唯一能做这种事情的人。
猜你喜欢
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多