[英]Download file from FTP if it does not exist in a given list of local files
我有一個FTP服務器,我想從中下載本地目錄中不存在的所有文件。
我嘗試做一個For Next
但是我無法理解。 我嘗試枚舉文件,但是由於對兩個列表都進行了處理,所以出現了錯誤。 我認為該錯誤可能是由交叉檢查在線文件與本地列表中的單個枚舉文件引起的。 如何消除這個問題?
鏈接到FTPClient類代碼:
https://docs.google.com/file/d/0BxFwEuHe1g77TEw2ckZxVUlQdGM/edit?usp=sharing
所有代碼:
Dim ftp As New FTPclient("ftp://www.ahpg.zxq.net", "eg", "eg")
Dim dirList As FTPdirectory = ftp.ListDirectoryDetail("/")
Dim result As List(Of String) = ftp.ListDirectory("/")
For Each line As String In result
FTPLBX.Items.Add(line)
Next
Dim str As String
Dim locstr As String
Dim res_numer As IEnumerator
res_numer = result.GetEnumerator()
Dim loclist As List(Of String) = New List(Of String) _
(System.IO.Directory.EnumerateFiles("C:/Program Files/Business Elements/Recent Files"))
Dim LOC_Enum As IEnumerator
LOC_Enum = loclist.GetEnumerator
Do While LOC_Enum.MoveNext
locstr = (LOC_Enum.Current)
Loop
Do While (res_numer.MoveNext)
str = (res_numer.Current)
Loop
For Each str In loclist
If Not loclist.Contains(str) = True Then
My.Computer.Network.DownloadFile("ftp://www.ahpg.zxq.net/ftpfiles/" & str.ToString, _
"C:/Program Files/Business Elements/Recent Files/" & str.ToString, "eg", "eg")
MessageBox.Show("Done ")
End If
Next
End Sub
如果適合您,我將它簡化了一點。 干得好:
' Your instance of FTPClient
Dim ftp As New FTPclient("ftp://www.ahpg.zxq.net", "eg", "eg")
' The path to destination folder (Local directory)
Dim localDir As String = "C:/Program Files/Business Elements/Recent Files/"
' Lists all the file in the given directory of FTP server
For Each file As FTPfileInfo In ftp.ListDirectoryDetail("/").GetFiles
Try
ftp.Download(file, localDir & file.Filename)
' The FTPClient class throws exception if the
' file already exists in destination directory
Catch e As ApplicationException
Console.WriteLine(e.Message)
End Try
Next file
注意1 :我從CodeProject
下載了FTPClient
類,但它與您在問題中提供的類幾乎相同。
注意2 :如果文件在目標文件夾中,則FTPClient
本身會引發異常。 因此,您無需費心比較文件。
注3 :請注意locadDir字符串末尾的斜杠 。 否則,文件將被下載到Business Element文件夾。
編寫一個子方法,我們稱其為IsExistedInLocal,以檢查ftp中的文件是否已在您的本地文件中。 如果是,請忽略並繼續進行下一個; 如果不是,請下載文件。我假設您知道所有詳細信息,因此偽代碼應該可以
for each FTP_file in FTP_FilesList
if not IsExistedInLocal(FTP_file) then
download the file to local
end if
next
在for循環中,您將獲取列表中的每個條目,然后檢查同一列表中沒有該元素。 您的if條件永遠不會為真,也永遠不會到達DownloadFile語句。
For Each str In loclist
If Not loclist.Contains(str) = True Then
My.Computer.Network.DownloadFile("ftp://www.ahpg.zxq.net/ftpfiles/" & str.ToString, _
"C:/Program Files/Business Elements/Recent Files/" & str.ToString, "eg", "eg")
MessageBox.Show("Done ")
End If
Next
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.