Wednesday, October 8, 2008

List FTP Directory contents

Public Function ListFTPDirectory(ByVal Dir As String) As String
Try
'Const localFile As String = "C:\myfile.bin"
'Const remoteFile As String = "/pub/myftpfile.bin"

Const username As String = "anonymous"
Const password As String = ""

'1. Create a request: must be in ftp://hostname format,

' not just ftp.myhost.com

Dim URI As String = Dir
Dim ftp As System.Net.FtpWebRequest = _
CType(FtpWebRequest.Create(URI), FtpWebRequest)

'2. Set credentials

ftp.Credentials = New System.Net.NetworkCredential(username, password)

'3. Settings and action

ftp.KeepAlive = False
'we want a binary transfer, not textual data

ftp.UseBinary = True
'Define the action required (in this case, list a directory)

ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory



'4. If we were using a method that uploads data e.g. UploadFile

' we would open the ftp.GetRequestStream here an send the data
'Dim encoder As New ASCIIEncoding
'Dim byteArray As Byte() = encoder.GetBytes(userInput)

'' Set the ContentLength property.
'myFileWebRequest.ContentLength = byteArray.Length

'Dim contentLength As String = myFileWebRequest.ContentLength.ToString()

'Console.WriteLine(ControlChars.Lf + "The content length is {0}.", contentLength)


'' Get the file stream handler to write to the file.
'Dim readStream As Stream = myFileWebRequest.GetRequestStream()

'' Write to the stream.
'' Note. For this to work the file must be accessible
'' on the network. This can be accomplished by setting the property
'' sharing of the folder containg the file.
'' FileWebRequest.Credentials property cannot be used for this purpose.
'readStream.Write(byteArray, 0, userInput.Length)


'5. Get the response to the Ftp request and the associated stream
Dim outString As String = ""
Dim stringWriter As New StringWriter()
Using response As System.Net.FtpWebResponse = _
CType(ftp.GetResponse, System.Net.FtpWebResponse)

'MsgBox("Response: " & response.StatusDescription)

Using responseStream As IO.Stream = response.GetResponseStream
' 'loop to read & write to file

' Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Dim enc As System.Text.ASCIIEncoding = New System.Text.ASCIIEncoding()

Do
read = responseStream.Read(buffer, 0, buffer.Length)

outString &= enc.GetString(buffer)


Loop Until read = 0 'see Note(1)


Return outString & response.StatusDescription
End Using

End Using

Catch ex As Exception
MsgBox(ex.Message.ToString())
Return String.Empty
End Try


End Function

No comments: