我想下載一個目錄,在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.
目標目錄是否存在於FTP服務器上?您正在使用的用戶是否擁有正確的權限? – Oded 2012-01-18 16:47:38
@Oded:確實如此,用戶確實如此。我以前列出目錄並創建目錄的CheckedListBox作爲選項。我也可以使用FileZilla手動獲取數據。 – Josh 2012-01-18 16:48:47