I am using this article to get a list of files in a directory using ftp.
If I run the code without some kind of delay, I only get about half the
files. If I put a debug.write statement it returns all the files. I think
this may be some kind of timing issue. Can anyone help?
URL:http://support.microsoft.com/?scid=kb;EN-US;832679
Here are the two sections of code that I am using:
'Return a list of files from the file system. Return these files in a
string() array.
Public Function GetFileList(ByVal sMask As String) As String()
Dim cSocket As Socket
Dim bytes As Int32
Dim seperator As Char = ControlChars.Lf
Dim mess() As String
Dim strCmd As String
If sMask Is Nothing Then
strCmd = "NLST"
'strCmd = "LIST"
Else
strCmd = "NLST " & sMask
End If
m_sMes = ""
'Check to see if you are logged on to the FTP server.
If (Not (m_bLoggedIn)) Then
Login()
End If
cSocket = CreateDataSocket()
'Send an FTP command.
'SendCommand("NLST " & sMask)
SendCommand(strCmd)
If (Not (m_iRetValue = 150 Or m_iRetValue = 125)) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
m_sMes = ""
Do While (True)
m_aBuffer.Clear(m_aBuffer, 0, m_aBuffer.Length)
bytes = cSocket.Receive(m_aBuffer, m_aBuffer.Length, 0)
m_sMes += ASCII.GetString(m_aBuffer, 0, bytes)
Debug.Write(ASCII.GetString(m_aBuffer, 0, bytes)) 'this will
affect the number of files returned. Maybe a timing issue?
If (bytes < m_aBuffer.Length) Then
Exit Do
End If
Loop
mess = m_sMes.Split(seperator)
cSocket.Close()
ReadReply()
If (m_iRetValue <> 226) Then
MessageString = m_sReply
Throw New IOException(m_sReply.Substring(4))
End If
Return mess
End Function
Private Sub cmdRun_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdRun.Click
Dim strFileList() As String
Try
'URL:http://support.microsoft.com/?scid=kb;EN-US;832679
ftpServer = New xxxFTP.clsFTP("IP Address", ".", "userId",
"password", 21)
If ftpServer.Login() Then
MessageBox.Show("sucessful login")
'strFileList length will be 88 (files) without the debug.write
statement and 157 with the debug statement
strFileList = ftpServer.GetFileList(Nothing) 'no mask
'strFileList = ftpServer.GetFileList("*.*") 'only files with
extension
Me.lstFiles.Items.Clear()
Dim str As String
For Each str In strFileList
If str.Trim <> "." And str.Trim <> ".." Then
Me.lstFiles.Items.Add(str)
End If
Next
Else
MessageBox.Show("unsucessful login")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
ftpServer.CloseConnection()
End Try
End Sub