473,695 Members | 2,492 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

VB.NET - Issues with VB.NET FTP Class to UNIX FTP Server

All,

I am currently developing an FTP class in VB.NET. It's kid tested,
mother approved when trying to access an FTP Server on a Windows box
meaning I can connect, run commands, upload and download a file no
problem. My issues come when I try to use the same class with the same
commands to access an FTP server on a UNIX box. I can connect and login
just fine, but after that all my commands come back "500 'PWD': command
not understood.". Has anyone experienced this error and can help me
solve it. In order to help everyone out the following is my class:

Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Text.ASC IIEncoding
Imports System.Net.Sock ets
Imports System.Configur ation
Imports System.Resource s

Public Class FTPClient

#Region "Local Properties"

'''<summary>
''' Public Property: Host - String variable.
'''</summary>
Public Property Host() As String
Get
Return _Host
End Get
Set(ByVal Value As String)
_Host = Value
End Set
End Property

'''<summary>
''' Public Property: Path - String variable.
'''</summary>
Public Property Path() As String
Get
Return _Path
End Get
Set(ByVal Value As String)
_Path = Value
End Set
End Property

'''<summary>
''' Public Property: User - String variable.
'''</summary>
Public Property User() As String
Get
Return _User
End Get
Set(ByVal Value As String)
_User = Value
End Set
End Property

'''<summary>
''' Public Property: Password - String variable.
'''</summary>
Public Property Password() As String
Get
Return _Password
End Get
Set(ByVal Value As String)
_Password = Value
End Set
End Property

'''<summary>
''' Public Property: Port - String variable.
'''</summary>
Public Property Port() As String
Get
Return _Port
End Get
Set(ByVal Value As String)
_Port = Value
End Set
End Property

'''<summary>
''' Public ReadOnly Property: ResponseCode - String variable.
'''</summary>
Public ReadOnly Property ResponseCode() As String
Get
Return _ResponseCode
End Get
End Property

'''<summary>
''' Public ReadOnly Property: ResponseData - String variable.
'''</summary>
Public ReadOnly Property ResponseData() As String
Get
Return _ResponseData
End Get
End Property

#End Region

' FTP Default Properties.
Private _Host As String = "127.0.0.1"
Private _Path As String = "."
Private _User As String = "anonymous"
Private _Password As String = "an*******@nowh ere.com"
Private _Port As Integer = 21
Private _ResponseCode As Integer
Private _ResponseData As String
Private _FTPCommandSock et As Socket = Nothing
Private _FTPLogin As Boolean = False

#Region "Public Methods"

Public Sub New()

End Sub

'''<summary>
''' Public Function: Login - This function will create a command
and data socket and then send the
''' login credentials to the FTP host.
'''</summary>
'''<returns>Fun ction returns a Boolean.</returns>
Public Function Login() As Boolean

' Create an FTP command socket.
CreateCommandSo cket()

' Send the gathered login information to the FTP host.
Try
SendCommand("US ER", _User)
SendCommand("PA SS", _Password)
_FTPLogin = True
Catch ex As Exception
' Login did not work because the FTP login information was
not accepted.
_ResponseData = "FTP Login function not executed."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP login information was not accepted", ex)
Return False
End Try

' Login successful.
Return True

End Function

'''<summary>
''' Public Sub: Logout - This subroutine will disconnect and close
an FTP command and data socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Public Sub Logout()

' Close and destroy the FTP command socket.
If (_FTPCommandSoc ket Is Nothing = False) Then
SendCommand("QU IT", "")
_FTPCommandSock et.Close()
_FTPCommandSock et = Nothing
End If
End Sub

'''<summary>
''' Public Sub: SendCommand - Provided a Command and Arguements,
this subroutine will execute an FTP Command.
''' Commands already taken care of with subroutines below:
''' TYPE: Mode (ASCII or Binary)
''' NLST: List files in directory
''' SIZE: Get file Size
''' RETR: Download a file
''' STOR: Upload a file
''' DELE: Delete a file
''' RNFR: Select a file to be renamed
''' RNTO: Rename a selected file
''' PWD: Get a current directory
''' CWD: Change directory
''' RDM: Remove a directory
'''</summary>
'''<param name="FTPComman d">As String</param>
'''<param name="FTPComman dArguements">As String</param>
'''<returns>Fun ction returns an FTP stream.</returns>
Public Sub SendCommand(ByV al FTPCommand As String, ByVal
FTPCommandArgum ents As String)

' Combine FTP command with the FTP command arguements.
Dim _FTPCommand As String = FTPCommand & " " &
FTPCommandArgum ents
_FTPCommand += Environment.New Line

' Convert the FTP command into ASCII text.
Dim commandBytes() As Byte = ASCII.GetBytes( _FTPCommand)

Try
' Execute the FTP command on the FTP host.
_FTPCommandSock et.Send(command Bytes, commandBytes.Le ngth,
0)
ReadResponse()
Catch ex As Exception
' Command was not executed.
_ResponseData = "FTP SendCommand subroutine not executed."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP command was not accepted", ex)
End Try
End Sub

'''<summary>
''' Public Sub: SetBinaryMode - This subroutine sets the FTP mode
to binary.
'''<param name="mode">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub SetBinaryMode(B yVal mode As Boolean)

If (mode) Then
'Send the FTP TYPE command as binary.
SendCommand("TY PE ", "I")
Else
'Send the FTP TYPE command as ASCII.
SendCommand("TY PE ", "A")
End If
End Sub

'''<summary>
''' Public Function: GetDirectoryFil eList - This function will get
the names of the files from the provided directory name.
'''</summary>
'''<param name="directory Name">As String</param>
'''<returns>Fun ction returns a string.</returns>
Public Function GetFileList(ByV al directoryName As String) As
String()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

'Send an FTP NLST command.
SendCommand("NL ST ", directoryName)

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If _FTPDataSocket. Connected Then
While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPDataSocket. Receive(_Buffer ,
_Buffer.Length, 0)
_Data += ASCII.GetString (_Buffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While
Else
_ResponseData = "FTP data socket failed to connect."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - GetFileList subroutine failed - FTP data
socket failed to connect.", "")
End If

Dim _Parts() As String = _Data.Split(_En dLine)

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

Return _Parts

End Function

'''<summary>
''' Public Function: GetFileSize - This function will get the size
of a provided file name.
'''</summary>
'''<param name="fileName" >As String</param>
'''<returns>Fun ction returns a Long.</returns>
' Get the size of the file on the FTP server.
Public Function GetFileSize(ByV al fileName As String) As Long

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

Dim _FileSize As Long

'Send an FTP SIZE command.
SendCommand("SI ZE ", fileName)
_FileSize = 0

Return _FileSize = Int64.Parse(_Re sponseData.Subs tring(4))

End Function

'''<summary>
''' Public Sub: DownloadFile - This subroutine gets a specific
file.
'''<param name="fileName" >As String</param>
'''<param name="filePath" >As String</param>
'''<optional param name="fileResum e">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub DownloadFile(By Val fileName As String, ByVal filePath As
String, Optional ByVal fileResume As Boolean = False)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Set the FTP mode to binary.
SetBinaryMode(T rue)

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

' Create a file.
Dim _FileStream As Stream
If (Not (File.Exists(fi lePath & fileName))) Then
_FileStream = File.Create(fil ePath & fileName)
_FileStream.Clo se()
End If

Dim _FTPFileStreamO utput As FileStream
_FTPFileStreamO utput = New FileStream(file Path & fileName,
FileMode.Open)

If fileResume Then
Dim _FileOffset As Long
_FileOffset = _FTPFileStreamO utput.Length

If (_FileOffset > 0) Then
' Send an FTP REST command to restart a file.
SendCommand("RE ST ", _FileOffset)
If (_ResponseCode <> 350) Then
'The FTP host does not support resuming.
_FileOffset = 0
End If
End If
If (_FileOffset <> 0) Then
_FTPFileStreamO utput.Seek(_Fil eOffset,
SeekOrigin.Begi n)
End If
End If

'Send an FTP RETR command to retrieve a file.
SendCommand("RE TR ", fileName)

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If _FTPDataSocket. Connected Then
While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPDataSocket. Receive(_Buffer ,
_Buffer.Length, 0)
_FTPFileStreamO utput.Write(_Bu ffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While
Else
_ResponseData = "FTP data socket failed to connect."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - GetFile subroutine failed - FTP data socket
failed to connect.", "")
End If

_FTPFileStreamO utput.Close()

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

End Sub

'''<summary>
''' Public Sub: UploadFile - This subroutine uploads a specific
file to an FTP host.
'''<param name="fileName" >As String</param>
'''<param name="filePath" >As String</param>
'''<optional param name="fileResum e">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub UploadFile(ByVa l fileName As String, ByVal filePath As
String, Optional ByVal fileResume As Boolean = False)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Set the FTP mode to binary.
SetBinaryMode(T rue)

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

' Check to see if the file exists locally before the upload.
If (File.Exists(fi lePath & fileName)) Then

' Open the input stream to read the source file.
Dim _FTPFileStreamI nput As FileStream
_FTPFileStreamI nput = New FileStream(file Path & fileName,
FileMode.Open)

If fileResume Then
' Check to see if part of the file has already been
uploaded.
Dim _FileOffset As Long
_FileOffset = 0

Try
_FileOffset = GetFileSize(fil eName)
Catch ex As Exception
_FileOffset = 0
End Try

If (_FileOffset > 0) Then
' Send an FTP REST command to restart a file.
SendCommand("RE ST ", _FileOffset)
If (_ResponseCode <> 350) Then
'The FTP host does not support resuming.
_FileOffset = 0
End If
End If

If (_FileOffset <> 0) Then
_FTPFileStreamI nput.Seek(_File Offset,
SeekOrigin.Begi n)
End If
End If

' Send an FTP STOR command to store a file.
SendCommand("ST OR ", fileName)

' Upload the file.
Const _BufferSize As Integer = 512
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

_BytesRead = _FTPFileStreamI nput.Read(_Buff er, 0,
_Buffer.Length)
If _FTPDataSocket. Connected Then
While (_BytesRead > 0)
_FTPDataSocket. Send(_Buffer, _BytesRead, 0)
_BytesRead = _FTPFileStreamI nput.Read(_Buff er, 0,
_Buffer.Length)
End While

Else
_ResponseData = "FTP data socket failed to
connect."
' Throw New
MPException(App Settings.Item(" Project"), "MP.IT.Web.Libr ary.FTP -
UploadFile subroutine failed - FTP data socket failed to connect.", "")
End If
_FTPFileStreamI nput.Close()

Else
_ResponseData = "File to upload does not exist on local
machine."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - UploadFile subroutine failed - file to upload
does not exist on local machine.", "")
End If

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

End Sub

'''<summary>
''' Public Sub: UploadFile - This subroutine deletes a specific
file on an FTP host.
'''<param name="fileName" >As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub DeleteFile(ByVa l fileName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Send an FTP DELE command to delete a file.
SendCommand("DE LE ", fileName)

End Sub

'''<summary>
''' Public Sub: RenameFile - This subroutine renames a specific
file on an FTP host.
'''<param name="fileName" >As String</param>
'''<param name="fileNewNa me">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub RenameFile(ByVa l fileName As String, ByVal fileNewName
As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Send an FTP RNFR command to select a file to be renamed.
SendCommand("RN FR ", fileName)

'Send an FTP RNTO command to rename the selected file to a new
file name.
SendCommand("RN TO ", fileNewName)

End Sub

'''<summary>
''' Public Sub: GetDirectory - This subroutine gets the current
directory on an FTP host.
'''<returns>Sub routine returns nothing.</returns>
Public Sub GetDirectory()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP CWD command to change to a directory.
SendCommand("PW D ", "")

End Sub

'''<summary>
''' Public Sub: ChangeDirectory - This subroutine changes to a
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub ChangeDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Check if in the root directory.
If (directoryName. Equals(".")) Then
Exit Sub
End If

'Send an FTP CWD command to change to a directory.
SendCommand("CW D ", directoryName)

End Sub

'''<summary>
''' Public Sub: CreateDirectory - This subroutine creates a new
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub CreateDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP MKD command to make a new directory.
SendCommand("MK D ", directoryName)

End Sub

'''<summary>
''' Public Sub: RemoveDirectory - This subroutine removes a
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub RemoveDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP RMD command to remove a directory.
SendCommand("RM D ", directoryName)

End Sub

#End Region

#Region "Private Methods"

'''<summary>
''' Private Sub: CreateCommandSo cket - Provided a Host and a port
this subroutine will instantiate an FTP command socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Private Sub CreateCommandSo cket()

' Create the FTP command socket.
_FTPCommandSock et = New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)

Try
Dim HostMachine As IPEndPoint = New
IPEndPoint(Dns. Resolve(_Host). AddressList(0), _Port)
Try
' Connect the FTP command socket to the FTP host
machine.
_FTPCommandSock et.Connect(Host Machine)
Catch ex As Exception
' Connection could not be opened due to malformed
connection.
_ResponseData = "FTP Command Socket Connection Could
Not Be Established."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Command Socket Connection Could Not Be
Established.", ex)
End Try
Catch ex As Exception
' Connection could not be opened because DNS cannot resolve
the host IP.
_ResponseData = "FTP Command Socket Connection Could Not Be
Established. Connection could not be opened because DNS cannot resolve
the host IP."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Command Socket Connection Could Not Be
Established. DNS cannot resolve the FTP host.", ex)
End Try
_ResponseData = "FTP Command Socket Connection Established."
ReadResponse()

End Sub

'''<summary>
''' Private Function: CreateDataSocke t - Provided that a PASV
command has been sent to the host, this function returns
''' an FTP data socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Private Function CreateDataSocke t() As Socket

Dim _FTPDataSocket As Socket
Dim _FTPHostIPFront Bracket As Integer
Dim _FTPHostIPBackB racket As Integer
Dim _FTPHostIPData As String
Dim _FTPHostIPLengt h As Integer
Dim _FTPHostIPPartC ount As Integer
Dim _FTPHostIPParts (6) As Integer
Dim _FTPHostIPChara ter As Char
Dim _Buffer As String
Dim _Counter As Integer

'Send an FTP PASV command to use passive data connection.
SendCommand("PA SV", "")

_FTPHostIPFront Bracket = _ResponseData.I ndexOf("(")
_FTPHostIPBackB racket = _ResponseData.I ndexOf(")")
_FTPHostIPData = _ResponseData.S ubstring(_FTPHo stIPFrontBracke t
+ 1, _FTPHostIPBackB racket - _FTPHostIPFront Bracket - 1)

_FTPHostIPLengt h = _FTPHostIPData. Length
_FTPHostIPPartC ount = 0
_Buffer = ""

For _Counter = 0 To ((_FTPHostIPLen gth - 1) And
_FTPHostIPPartC ount <= 6)
_FTPHostIPChara ter =
Char.Parse(_FTP HostIPData.Subs tring(_Counter, 1))
If (Char.IsDigit(_ FTPHostIPCharat er)) Then
_Buffer += _FTPHostIPChara ter
ElseIf (_FTPHostIPChar ater <> ",") Then
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Host did not accept the PASV command.",
"")
End If

If ((_FTPHostIPCha rater = ",") Or (_Counter + 1 =
_FTPHostIPLengt h)) Then
Try
_FTPHostIPParts (_FTPHostIPPart Count) =
Int32.Parse(_Bu ffer)
_FTPHostIPPartC ount += 1
_Buffer = ""
Catch ex As Exception
' Throw New
MPException(App Settings.Item(" Project"), "MP.IT.Web.Libr ary.FTP - FTP
Host did not accept the PASV command.", ex)
End Try
End If
Next

' Create the data host.
Dim _DataHost As String = _FTPHostIPParts (0) & "." &
_FTPHostIPParts (1) & "." & _FTPHostIPParts (2) & "." &
_FTPHostIPParts (3)

' Create the data port.
Dim _DataPort As Integer = _FTPHostIPParts (4) << 8

' Determine the data port number.
_DataPort = _DataPort + _FTPHostIPParts (5)

' Create the FTP data socket from the data host and data port.
_FTPDataSocket = New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)

Try
Dim HostMachine As IPEndPoint = New
IPEndPoint(Dns. Resolve(_DataHo st).AddressList (0), _DataPort)
Try
' Connect the FTP data socket to the FTP host machine.
_FTPDataSocket. Connect(HostMac hine)
Return _FTPDataSocket
Catch ex As Exception
' Connection could not be opened due to malformed
connection.
_ResponseData = "FTP Data Socket Connection Could Not
Be Established."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Data Socket Connection Could Not Be
Established.", ex)
End Try
Catch ex As Exception
' Connection could not be opened because DNS cannot resolve
the host IP.
_ResponseData = "FTP Data Socket Connection Could Not Be
Established. Connection could not be opened because DNS cannot resolve
the host IP."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Data Socket Connection Could Not Be
Established. DNS cannot resolve the FTP host.", ex)
End Try
_ResponseData = "FTP Data Socket Connection Established."

End Function

'''<summary>
''' Private Sub: ReadResponse - This subroutine will read line by
line the reply to
''' a command sent to an FTP host.
'''</summary>
'''<returns>Fun ction returns a string.</returns>
Private Sub ReadResponse()

' Read the response from the FTP host.
_ResponseData = ReadLine(False)
_ResponseCode = Int32.Parse(_Re sponseData.Subs tring(0, 3))

End Sub

'''<summary>
''' Private Function: ReadLine - This function handles the actual
reading of the FTP host reply.
'''</summary>
'''<param name="clearResp onse">As Boolean</param>
'''<returns>Fun ction returns a string.</returns>
Private Function ReadLine(ByVal clearResponse As Boolean) As String

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If (clearResponse = True) Then _ResponseData = String.Empty

While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPCommandSock et.Receive(_Buf fer,
_Buffer.Length, 0)
_Data += ASCII.GetString (_Buffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While

Dim _Parts() As String = _Data.Split(_En dLine)

If (_Parts.Length > 2) Then
_ResponseData = _Parts(_Parts.L ength - 2)
Else
_ResponseData = _Parts(0)
End If

If (_ResponseData. Substring(3, 1).Equals(" ") = False) Then
Return ReadLine(False)
End If

Return _ResponseData
End Function

#End Region

End Class

Mar 22 '06 #1
9 8325

cr***********@g mail.com wrote:
All,

I am currently developing an FTP class in VB.NET. It's kid tested,
mother approved when trying to access an FTP Server on a Windows box
meaning I can connect, run commands, upload and download a file no
problem. My issues come when I try to use the same class with the same
commands to access an FTP server on a UNIX box. I can connect and login
just fine, but after that all my commands come back "500 'PWD': command
not understood.". Has anyone experienced this error and can help me
solve it. In order to help everyone out the following is my class:


<snip>

Craig...

Is there a reason you are implementing this code when there are free
and working ftp clients available for .NET (Indy project comes to
mind)? If this is for personal learning I will be glad to look over
this code, but it might take a little debugging time :)

--
Tom Shelton [MVP]

Mar 22 '06 #2
Tom,

You hit the nail on the head, I am learning, but I just can't seem to
understand how it works so well with a Windows environment FTP server
and then won't get passed the password command in the UNIX environment
FTP. Take as much time as you want. I am interested to know and the
code should be cut and paste for you.

Craig

Mar 22 '06 #3

craig.over...@g mail.com wrote:
Tom,

You hit the nail on the head, I am learning, but I just can't seem to
understand how it works so well with a Windows environment FTP server
and then won't get passed the password command in the UNIX environment
FTP. Take as much time as you want. I am interested to know and the
code should be cut and paste for you.

Craig


Well... Actually, it's a bit hard to cut and past through Google.
But, I've almost got it to compile :)

My first response - since I haven't got it to compile just yet is, you
obviously didn't have Option Strict turned on. I would suggest that
you make this a habbit for most code. Anyway, I'll get back to you
once I've got a clean compile.

--
Tom Shelton [MVP]

Mar 22 '06 #4
Tom,

You hit the nail on the head, I am learning, but I just can't seem to
understand how it works so well with a Windows environment FTP server
and then won't get passed the password command in the UNIX environment
FTP. Take as much time as you want. I am interested to know and the
code should be cut and paste for you.

Craig

Mar 22 '06 #5
Tom,

Don't bother. I found my mistake and I am pretty much an idiot for it.
Basically I have my subroutine for sending commands called SendCommand.
In that sub I take care of adding the space character after the command
before the command arguements. Well I really should have cleaned up
that sub to make it more efficient. Basically not all FTP commands have
arguements so I really shouldn't being adding that space unless there
are arguements. To make matters even more fun, in all my subroutines
thereafter I added a space after the FTP command and then shipped it to
the SendCommand sub which was already messed up, thus actually doubling
the space character between the FTP command and the FTP command
arguements if there were arguements. Somehow Windows based FTP servers
let this fly whereas Unix FTP servers cannot even understand what was
sent to it as a command. The fixed code that is working across the
board is below. There isn't much it doesn't do. I should probably add
events and a lot more error checking, but it will do for now: Tom thank
you for at least taking some time to look at it.

Craig

Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Text.ASC IIEncoding
Imports System.Net.Sock ets
Imports System.Configur ation
Imports System.Resource s

Public Class FTPClient

#Region "Local Properties"

'''<summary>
''' Public Property: Host - String variable.
'''</summary>
Public Property Host() As String
Get
Return _Host
End Get
Set(ByVal Value As String)
_Host = Value
End Set
End Property

'''<summary>
''' Public Property: Path - String variable.
'''</summary>
Public Property Path() As String
Get
Return _Path
End Get
Set(ByVal Value As String)
_Path = Value
End Set
End Property

'''<summary>
''' Public Property: User - String variable.
'''</summary>
Public Property User() As String
Get
Return _User
End Get
Set(ByVal Value As String)
_User = Value
End Set
End Property

'''<summary>
''' Public Property: Password - String variable.
'''</summary>
Public Property Password() As String
Get
Return _Password
End Get
Set(ByVal Value As String)
_Password = Value
End Set
End Property

'''<summary>
''' Public Property: Port - String variable.
'''</summary>
Public Property Port() As String
Get
Return _Port
End Get
Set(ByVal Value As String)
_Port = Value
End Set
End Property

'''<summary>
''' Public ReadOnly Property: ResponseCode - String variable.
'''</summary>
Public ReadOnly Property ResponseCode() As String
Get
Return _ResponseCode
End Get
End Property

'''<summary>
''' Public ReadOnly Property: ResponseData - String variable.
'''</summary>
Public ReadOnly Property ResponseData() As String
Get
Return _ResponseData
End Get
End Property

#End Region

' FTP Default Properties.
Private _Host As String = "127.0.0.1"
Private _Path As String = "."
Private _User As String = "anonymous"
Private _Password As String = "an*******@nowh ere.com"
Private _Port As Integer = 21
Private _ResponseCode As Integer
Private _ResponseData As String
Private _FTPCommandSock et As Socket = Nothing
Private _FTPLogin As Boolean = False
Private _FTPCommandSock etInstalled As Boolean = False

#Region "Public Methods"

Public Sub New()

End Sub

'''<summary>
''' Public Function: Login - This function will create a command
and data socket and then send the
''' login credentials to the FTP host.
'''</summary>
'''<returns>Fun ction returns a Boolean.</returns>
Public Function Login() As Boolean

' Create an FTP command socket.
CreateCommandSo cket()

' Send the gathered login information to the FTP host.
Try
SendCommand("US ER", _User)
SendCommand("PA SS", _Password)
_FTPLogin = True
Catch ex As Exception
' Login did not work because the FTP login information was
not accepted.
_ResponseData = "FTP Login function not executed."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP login information was not accepted", ex)
Return False
End Try

' Login successful.
Return True

End Function

'''<summary>
''' Public Sub: Logout - This subroutine will disconnect and close
an FTP command and data socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Public Sub Logout()

' Close and destroy the FTP command socket.
If (_FTPCommandSoc ket Is Nothing = False) Then
SendCommand("QU IT", "")
_FTPCommandSock et.Close()
_FTPCommandSock et = Nothing
End If
End Sub

'''<summary>
''' Public Sub: SendCommand - Provided a Command and Arguements,
this subroutine will execute an FTP Command.
''' Commands already taken care of with subroutines below:
''' TYPE: Mode (ASCII or Binary)
''' NLST: List files in directory
''' SIZE: Get file Size
''' RETR: Download a file
''' STOR: Upload a file
''' DELE: Delete a file
''' RNFR: Select a file to be renamed
''' RNTO: Rename a selected file
''' PWD: Get a current directory
''' CWD: Change directory
''' RDM: Remove a directory
'''</summary>
'''<param name="FTPComman d">As String</param>
'''<param name="FTPComman dArguements">As String</param>
'''<returns>Fun ction returns an FTP stream.</returns>
Public Sub SendCommand(ByV al FTPCommand As String, ByVal
FTPCommandArgum ents As String)

Dim _FTPCommand As String
' Combine FTP command with the FTP command arguements.
If FTPCommandArgum ents = String.Empty Then
_FTPCommand = FTPCommand
Else
_FTPCommand = FTPCommand & " " & FTPCommandArgum ents
End If
_FTPCommand += Environment.New Line

' Convert the FTP command into ASCII text.
Dim commandBytes() As Byte = ASCII.GetBytes( _FTPCommand)

Try
' Execute the FTP command on the FTP host.
_FTPCommandSock et.Send(command Bytes, commandBytes.Le ngth,
0)
ReadResponse()
Catch ex As Exception
' Command was not executed.
_ResponseData = "FTP SendCommand subroutine not executed."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP command was not accepted", ex)
End Try
End Sub

'''<summary>
''' Public Sub: SetBinaryMode - This subroutine sets the FTP mode
to binary.
'''<param name="mode">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub SetBinaryMode(B yVal mode As Boolean)

If (mode) Then
'Send the FTP TYPE command as binary.
SendCommand("TY PE", "I")
Else
'Send the FTP TYPE command as ASCII.
SendCommand("TY PE", "A")
End If
End Sub

'''<summary>
''' Public Function: GetDirectoryFil eList - This function will get
the names of the files from the provided directory name.
'''</summary>
'''<param name="directory Name">As String</param>
'''<returns>Fun ction returns a string.</returns>
Public Function GetFileList(ByV al directoryName As String) As
String()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

'Send an FTP NLST command.
SendCommand("NL ST", directoryName)

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If _FTPDataSocket. Connected Then
While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPDataSocket. Receive(_Buffer ,
_Buffer.Length, 0)
_Data += ASCII.GetString (_Buffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While
Else
_ResponseData = "FTP data socket failed to connect."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - GetFileList subroutine failed - FTP data
socket failed to connect.", "")
End If

Dim _Parts() As String = _Data.Split(_En dLine)

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

Return _Parts

End Function

'''<summary>
''' Public Function: GetFileSize - This function will get the size
of a provided file name.
'''</summary>
'''<param name="fileName" >As String</param>
'''<returns>Fun ction returns a Long.</returns>
' Get the size of the file on the FTP server.
Public Function GetFileSize(ByV al fileName As String) As Long

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

Dim _FileSize As Long

'Send an FTP SIZE command.
SendCommand("SI ZE", fileName)
_FileSize = 0

Return _FileSize = Int64.Parse(_Re sponseData.Subs tring(4))

End Function

'''<summary>
''' Public Sub: DownloadFile - This subroutine gets a specific
file.
'''<param name="fileName" >As String</param>
'''<param name="filePath" >As String</param>
'''<optional param name="fileResum e">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub DownloadFile(By Val fileName As String, ByVal filePath As
String, Optional ByVal fileResume As Boolean = False)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Set the FTP mode to binary.
SetBinaryMode(T rue)

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

' Create a file.
Dim _FileStream As Stream
If (Not (File.Exists(fi lePath & fileName))) Then
_FileStream = File.Create(fil ePath & fileName)
_FileStream.Clo se()
End If

Dim _FTPFileStreamO utput As FileStream
_FTPFileStreamO utput = New FileStream(file Path & fileName,
FileMode.Open)

If fileResume Then
Dim _FileOffset As Long
_FileOffset = _FTPFileStreamO utput.Length

If (_FileOffset > 0) Then
' Send an FTP REST command to restart a file.
SendCommand("RE ST", _FileOffset)
If (_ResponseCode <> 350) Then
'The FTP host does not support resuming.
_FileOffset = 0
End If
End If
If (_FileOffset <> 0) Then
_FTPFileStreamO utput.Seek(_Fil eOffset,
SeekOrigin.Begi n)
End If
End If

'Send an FTP RETR command to retrieve a file.
SendCommand("RE TR", fileName)

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If _FTPDataSocket. Connected Then
While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPDataSocket. Receive(_Buffer ,
_Buffer.Length, 0)
_FTPFileStreamO utput.Write(_Bu ffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While
Else
_ResponseData = "FTP data socket failed to connect."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - GetFile subroutine failed - FTP data socket
failed to connect.", "")
End If

_FTPFileStreamO utput.Close()

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

End Sub

'''<summary>
''' Public Sub: UploadFile - This subroutine uploads a specific
file to an FTP host.
'''<param name="fileName" >As String</param>
'''<param name="filePath" >As String</param>
'''<optional param name="fileResum e">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub UploadFile(ByVa l fileName As String, ByVal filePath As
String, Optional ByVal fileResume As Boolean = False)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Set the FTP mode to binary.
SetBinaryMode(T rue)

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

' Check to see if the file exists locally before the upload.
If (File.Exists(fi lePath & fileName)) Then

' Open the input stream to read the source file.
Dim _FTPFileStreamI nput As FileStream
_FTPFileStreamI nput = New FileStream(file Path & fileName,
FileMode.Open)

If fileResume Then
' Check to see if part of the file has already been
uploaded.
Dim _FileOffset As Long
_FileOffset = 0

Try
_FileOffset = GetFileSize(fil eName)
Catch ex As Exception
_FileOffset = 0
End Try

If (_FileOffset > 0) Then
' Send an FTP REST command to restart a file.
SendCommand("RE ST", _FileOffset)
If (_ResponseCode <> 350) Then
'The FTP host does not support resuming.
_FileOffset = 0
End If
End If

If (_FileOffset <> 0) Then
_FTPFileStreamI nput.Seek(_File Offset,
SeekOrigin.Begi n)
End If
End If

' Send an FTP STOR command to store a file.
SendCommand("ST OR", fileName)

' Upload the file.
Const _BufferSize As Integer = 512
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

_BytesRead = _FTPFileStreamI nput.Read(_Buff er, 0,
_Buffer.Length)
If _FTPDataSocket. Connected Then
While (_BytesRead > 0)
_FTPDataSocket. Send(_Buffer, _BytesRead, 0)
_BytesRead = _FTPFileStreamI nput.Read(_Buff er, 0,
_Buffer.Length)
End While

Else
_ResponseData = "FTP data socket failed to
connect."
' Throw New
MPException(App Settings.Item(" Project"), "MP.IT.Web.Libr ary.FTP -
UploadFile subroutine failed - FTP data socket failed to connect.", "")
End If
_FTPFileStreamI nput.Close()

Else
_ResponseData = "File to upload does not exist on local
machine."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - UploadFile subroutine failed - file to upload
does not exist on local machine.", "")
End If

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

End Sub

'''<summary>
''' Public Sub: UploadFile - This subroutine deletes a specific
file on an FTP host.
'''<param name="fileName" >As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub DeleteFile(ByVa l fileName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Send an FTP DELE command to delete a file.
SendCommand("DE LE", fileName)

End Sub

'''<summary>
''' Public Sub: RenameFile - This subroutine renames a specific
file on an FTP host.
'''<param name="fileName" >As String</param>
'''<param name="fileNewNa me">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub RenameFile(ByVa l fileName As String, ByVal fileNewName
As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Send an FTP RNFR command to select a file to be renamed.
SendCommand("RN FR", fileName)

'Send an FTP RNTO command to rename the selected file to a new
file name.
SendCommand("RN TO", fileNewName)

End Sub

'''<summary>
''' Public Sub: GetDirectory - This subroutine gets the current
directory on an FTP host.
'''<returns>Sub routine returns nothing.</returns>
Public Sub GetDirectory()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP CWD command to change to a directory.
SendCommand("PW D", "")

End Sub

'''<summary>
''' Public Sub: ChangeDirectory - This subroutine changes to a
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub ChangeDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Check if in the root directory.
If (directoryName. Equals(".")) Then
Exit Sub
End If

'Send an FTP CWD command to change to a directory.
SendCommand("CW D", directoryName)

End Sub

'''<summary>
''' Public Sub: CreateDirectory - This subroutine creates a new
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub CreateDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP MKD command to make a new directory.
SendCommand("MK D", directoryName)

End Sub

'''<summary>
''' Public Sub: RemoveDirectory - This subroutine removes a
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub RemoveDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP RMD command to remove a directory.
SendCommand("RM D", directoryName)

End Sub

#End Region

#Region "Private Methods"

'''<summary>
''' Private Sub: CreateCommandSo cket - Provided a Host and a port
this subroutine will instantiate an FTP command socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Private Sub CreateCommandSo cket()

' Create the FTP command socket.
_FTPCommandSock et = New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)

Try
Dim HostMachine As IPEndPoint = New
IPEndPoint(Dns. Resolve(_Host). AddressList(0), _Port)
Try
' Connect the FTP command socket to the FTP host
machine.
_FTPCommandSock et.Connect(Host Machine)
Catch ex As Exception
' Connection could not be opened due to malformed
connection.
_ResponseData = "FTP Command Socket Connection Could
Not Be Established."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Command Socket Connection Could Not Be
Established.", ex)
End Try
Catch ex As Exception
' Connection could not be opened because DNS cannot resolve
the host IP.
_ResponseData = "FTP Command Socket Connection Could Not Be
Established. Connection could not be opened because DNS cannot resolve
the host IP."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Command Socket Connection Could Not Be
Established. DNS cannot resolve the FTP host.", ex)
End Try
_ResponseData = "FTP Command Socket Connection Established."
ReadResponse()

End Sub

'''<summary>
''' Private Function: CreateDataSocke t - Provided that a PASV
command has been sent to the host, this function returns
''' an FTP data socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Private Function CreateDataSocke t() As Socket

Dim _FTPDataSocket As Socket
Dim _FTPHostIPFront Bracket As Integer
Dim _FTPHostIPBackB racket As Integer
Dim _FTPHostIPData As String
Dim _FTPHostIPLengt h As Integer
Dim _FTPHostIPPartC ount As Integer
Dim _FTPHostIPParts (6) As Integer
Dim _FTPHostIPChara ter As Char
Dim _Buffer As String
Dim _Counter As Integer

'Send an FTP PASV command to use passive data connection.
SendCommand("PA SV", "")

_FTPHostIPFront Bracket = _ResponseData.I ndexOf("(")
_FTPHostIPBackB racket = _ResponseData.I ndexOf(")")
_FTPHostIPData = _ResponseData.S ubstring(_FTPHo stIPFrontBracke t
+ 1, _FTPHostIPBackB racket - _FTPHostIPFront Bracket - 1)

_FTPHostIPLengt h = _FTPHostIPData. Length
_FTPHostIPPartC ount = 0
_Buffer = ""

For _Counter = 0 To ((_FTPHostIPLen gth - 1) And
_FTPHostIPPartC ount <= 6)
_FTPHostIPChara ter =
Char.Parse(_FTP HostIPData.Subs tring(_Counter, 1))
If (Char.IsDigit(_ FTPHostIPCharat er)) Then
_Buffer += _FTPHostIPChara ter
ElseIf (_FTPHostIPChar ater <> ",") Then
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Host did not accept the PASV command.",
"")
End If

If ((_FTPHostIPCha rater = ",") Or (_Counter + 1 =
_FTPHostIPLengt h)) Then
Try
_FTPHostIPParts (_FTPHostIPPart Count) =
Int32.Parse(_Bu ffer)
_FTPHostIPPartC ount += 1
_Buffer = ""
Catch ex As Exception
' Throw New
MPException(App Settings.Item(" Project"), "MP.IT.Web.Libr ary.FTP - FTP
Host did not accept the PASV command.", ex)
End Try
End If
Next

' Create the data host.
Dim _DataHost As String = _FTPHostIPParts (0) & "." &
_FTPHostIPParts (1) & "." & _FTPHostIPParts (2) & "." &
_FTPHostIPParts (3)

' Create the data port.
Dim _DataPort As Integer = _FTPHostIPParts (4) << 8

' Determine the data port number.
_DataPort = _DataPort + _FTPHostIPParts (5)

' Create the FTP data socket from the data host and data port.
_FTPDataSocket = New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)

Try
Dim HostMachine As IPEndPoint = New
IPEndPoint(Dns. Resolve(_DataHo st).AddressList (0), _DataPort)
Try
' Connect the FTP data socket to the FTP host machine.
_FTPDataSocket. Connect(HostMac hine)
Return _FTPDataSocket
Catch ex As Exception
' Connection could not be opened due to malformed
connection.
_ResponseData = "FTP Data Socket Connection Could Not
Be Established."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Data Socket Connection Could Not Be
Established.", ex)
End Try
Catch ex As Exception
' Connection could not be opened because DNS cannot resolve
the host IP.
_ResponseData = "FTP Data Socket Connection Could Not Be
Established. Connection could not be opened because DNS cannot resolve
the host IP."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Data Socket Connection Could Not Be
Established. DNS cannot resolve the FTP host.", ex)
End Try
_ResponseData = "FTP Data Socket Connection Established."

End Function

'''<summary>
''' Private Sub: ReadResponse - This subroutine will read line by
line the reply to
''' a command sent to an FTP host.
'''</summary>
'''<returns>Fun ction returns a string.</returns>
Private Sub ReadResponse()

' Read the response from the FTP host.
_ResponseData = ReadLine(False)
_ResponseCode = Int32.Parse(_Re sponseData.Subs tring(0, 3))

End Sub

'''<summary>
''' Private Function: ReadLine - This function handles the actual
reading of the FTP host reply.
'''</summary>
'''<param name="clearResp onse">As Boolean</param>
'''<returns>Fun ction returns a string.</returns>
Private Function ReadLine(ByVal clearResponse As Boolean) As String

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If (clearResponse = True) Then _ResponseData = String.Empty

While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPCommandSock et.Receive(_Buf fer,
_Buffer.Length, 0)
_Data += ASCII.GetString (_Buffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While

Dim _Parts() As String = _Data.Split(_En dLine)

If (_Parts.Length > 2) Then
_ResponseData = _Parts(_Parts.L ength - 2)
Else
_ResponseData = _Parts(0)
End If

If (_ResponseData. Substring(3, 1).Equals(" ") = False) Then
Return ReadLine(False)
End If

Return _ResponseData
End Function

#End Region

End Class

Mar 22 '06 #6

cr***********@g mail.com wrote:
All,

I am currently developing an FTP class in VB.NET. It's kid tested,
mother approved when trying to access an FTP Server on a Windows box
meaning I can connect, run commands, upload and download a file no
problem. My issues come when I try to use the same class with the same
commands to access an FTP server on a UNIX box. I can connect and login
just fine, but after that all my commands come back "500 'PWD': command
not understood.". Has anyone experienced this error and can help me
solve it. In order to help everyone out the following is my class:
Ok... I won't repost all of the code, but here is the basic problem.
You have extra spaces in the command strings. This happens because you
are passing data like this:

Public Sub GetDirectory()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP CWD command to change to a directory.
SendCommand("PW D ", "")

End Sub

This should really be:

Public Sub GetDirectory()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP CWD command to change to a directory.
SendCommand("PW D", "")

End Sub

Of course - this doesn't completely fix your problem. I modified your
SendCommand a little bit as well:

Public Sub SendCommand(ByV al FTPCommand As String, ByVal
FTPCommandArgum ents As String)

' Combine FTP command with the FTP command arguements.
Dim _FTPCommand As String = IIf(FTPCommandA rguments.Length 0, FTPCommand & " " & FTPCommandArgum ents, FTPCommand)

_FTPCommand += Environment.New Line

' Convert the FTP command into ASCII text.
Dim commandBytes() As Byte = ASCII.GetBytes( _FTPCommand)

Try
' Execute the FTP command on the FTP host.
_FTPCommandSock et.Send(command Bytes,
commandBytes.Le ngth, 0)
ReadResponse()
Catch ex As Exception
' Command was not executed.
_ResponseData = "FTP SendCommand subroutine not
executed."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP command was not accepted", ex)
End Try
End Sub

I can make a lot more suggestions about how to code this - but this
should fix your immediate issue (go through and fix all the methods to
not pass the command + space, but just the command). Apparently, UNIX
ftp servers - and I could recreate this going to our SCO server - are
picky about the extra spaces, and windows ftp server is not.

--
Tom Shelton [MVP]

Mar 22 '06 #7
Craig,

Did you try use the sample FTP from the 101 2005 samples kit.

http://msdn.microsoft.com/vstudio/do...s/default.aspx

Be aware that this are often with a converter from C# converted samples
therefore don't use these as samples how to write VBNet programs. But they
are nice to learn the classes.

I hope this helps,

Cor

<cr***********@ gmail.com> schreef in bericht
news:11******** **************@ i39g2000cwa.goo glegroups.com.. .
All,

I am currently developing an FTP class in VB.NET. It's kid tested,
mother approved when trying to access an FTP Server on a Windows box
meaning I can connect, run commands, upload and download a file no
problem. My issues come when I try to use the same class with the same
commands to access an FTP server on a UNIX box. I can connect and login
just fine, but after that all my commands come back "500 'PWD': command
not understood.". Has anyone experienced this error and can help me
solve it. In order to help everyone out the following is my class:

Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Text.ASC IIEncoding
Imports System.Net.Sock ets
Imports System.Configur ation
Imports System.Resource s

Public Class FTPClient

#Region "Local Properties"

'''<summary>
''' Public Property: Host - String variable.
'''</summary>
Public Property Host() As String
Get
Return _Host
End Get
Set(ByVal Value As String)
_Host = Value
End Set
End Property

'''<summary>
''' Public Property: Path - String variable.
'''</summary>
Public Property Path() As String
Get
Return _Path
End Get
Set(ByVal Value As String)
_Path = Value
End Set
End Property

'''<summary>
''' Public Property: User - String variable.
'''</summary>
Public Property User() As String
Get
Return _User
End Get
Set(ByVal Value As String)
_User = Value
End Set
End Property

'''<summary>
''' Public Property: Password - String variable.
'''</summary>
Public Property Password() As String
Get
Return _Password
End Get
Set(ByVal Value As String)
_Password = Value
End Set
End Property

'''<summary>
''' Public Property: Port - String variable.
'''</summary>
Public Property Port() As String
Get
Return _Port
End Get
Set(ByVal Value As String)
_Port = Value
End Set
End Property

'''<summary>
''' Public ReadOnly Property: ResponseCode - String variable.
'''</summary>
Public ReadOnly Property ResponseCode() As String
Get
Return _ResponseCode
End Get
End Property

'''<summary>
''' Public ReadOnly Property: ResponseData - String variable.
'''</summary>
Public ReadOnly Property ResponseData() As String
Get
Return _ResponseData
End Get
End Property

#End Region

' FTP Default Properties.
Private _Host As String = "127.0.0.1"
Private _Path As String = "."
Private _User As String = "anonymous"
Private _Password As String = "an*******@nowh ere.com"
Private _Port As Integer = 21
Private _ResponseCode As Integer
Private _ResponseData As String
Private _FTPCommandSock et As Socket = Nothing
Private _FTPLogin As Boolean = False

#Region "Public Methods"

Public Sub New()

End Sub

'''<summary>
''' Public Function: Login - This function will create a command
and data socket and then send the
''' login credentials to the FTP host.
'''</summary>
'''<returns>Fun ction returns a Boolean.</returns>
Public Function Login() As Boolean

' Create an FTP command socket.
CreateCommandSo cket()

' Send the gathered login information to the FTP host.
Try
SendCommand("US ER", _User)
SendCommand("PA SS", _Password)
_FTPLogin = True
Catch ex As Exception
' Login did not work because the FTP login information was
not accepted.
_ResponseData = "FTP Login function not executed."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP login information was not accepted", ex)
Return False
End Try

' Login successful.
Return True

End Function

'''<summary>
''' Public Sub: Logout - This subroutine will disconnect and close
an FTP command and data socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Public Sub Logout()

' Close and destroy the FTP command socket.
If (_FTPCommandSoc ket Is Nothing = False) Then
SendCommand("QU IT", "")
_FTPCommandSock et.Close()
_FTPCommandSock et = Nothing
End If
End Sub

'''<summary>
''' Public Sub: SendCommand - Provided a Command and Arguements,
this subroutine will execute an FTP Command.
''' Commands already taken care of with subroutines below:
''' TYPE: Mode (ASCII or Binary)
''' NLST: List files in directory
''' SIZE: Get file Size
''' RETR: Download a file
''' STOR: Upload a file
''' DELE: Delete a file
''' RNFR: Select a file to be renamed
''' RNTO: Rename a selected file
''' PWD: Get a current directory
''' CWD: Change directory
''' RDM: Remove a directory
'''</summary>
'''<param name="FTPComman d">As String</param>
'''<param name="FTPComman dArguements">As String</param>
'''<returns>Fun ction returns an FTP stream.</returns>
Public Sub SendCommand(ByV al FTPCommand As String, ByVal
FTPCommandArgum ents As String)

' Combine FTP command with the FTP command arguements.
Dim _FTPCommand As String = FTPCommand & " " &
FTPCommandArgum ents
_FTPCommand += Environment.New Line

' Convert the FTP command into ASCII text.
Dim commandBytes() As Byte = ASCII.GetBytes( _FTPCommand)

Try
' Execute the FTP command on the FTP host.
_FTPCommandSock et.Send(command Bytes, commandBytes.Le ngth,
0)
ReadResponse()
Catch ex As Exception
' Command was not executed.
_ResponseData = "FTP SendCommand subroutine not executed."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP command was not accepted", ex)
End Try
End Sub

'''<summary>
''' Public Sub: SetBinaryMode - This subroutine sets the FTP mode
to binary.
'''<param name="mode">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub SetBinaryMode(B yVal mode As Boolean)

If (mode) Then
'Send the FTP TYPE command as binary.
SendCommand("TY PE ", "I")
Else
'Send the FTP TYPE command as ASCII.
SendCommand("TY PE ", "A")
End If
End Sub

'''<summary>
''' Public Function: GetDirectoryFil eList - This function will get
the names of the files from the provided directory name.
'''</summary>
'''<param name="directory Name">As String</param>
'''<returns>Fun ction returns a string.</returns>
Public Function GetFileList(ByV al directoryName As String) As
String()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

'Send an FTP NLST command.
SendCommand("NL ST ", directoryName)

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If _FTPDataSocket. Connected Then
While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPDataSocket. Receive(_Buffer ,
_Buffer.Length, 0)
_Data += ASCII.GetString (_Buffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While
Else
_ResponseData = "FTP data socket failed to connect."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - GetFileList subroutine failed - FTP data
socket failed to connect.", "")
End If

Dim _Parts() As String = _Data.Split(_En dLine)

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

Return _Parts

End Function

'''<summary>
''' Public Function: GetFileSize - This function will get the size
of a provided file name.
'''</summary>
'''<param name="fileName" >As String</param>
'''<returns>Fun ction returns a Long.</returns>
' Get the size of the file on the FTP server.
Public Function GetFileSize(ByV al fileName As String) As Long

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

Dim _FileSize As Long

'Send an FTP SIZE command.
SendCommand("SI ZE ", fileName)
_FileSize = 0

Return _FileSize = Int64.Parse(_Re sponseData.Subs tring(4))

End Function

'''<summary>
''' Public Sub: DownloadFile - This subroutine gets a specific
file.
'''<param name="fileName" >As String</param>
'''<param name="filePath" >As String</param>
'''<optional param name="fileResum e">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub DownloadFile(By Val fileName As String, ByVal filePath As
String, Optional ByVal fileResume As Boolean = False)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Set the FTP mode to binary.
SetBinaryMode(T rue)

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

' Create a file.
Dim _FileStream As Stream
If (Not (File.Exists(fi lePath & fileName))) Then
_FileStream = File.Create(fil ePath & fileName)
_FileStream.Clo se()
End If

Dim _FTPFileStreamO utput As FileStream
_FTPFileStreamO utput = New FileStream(file Path & fileName,
FileMode.Open)

If fileResume Then
Dim _FileOffset As Long
_FileOffset = _FTPFileStreamO utput.Length

If (_FileOffset > 0) Then
' Send an FTP REST command to restart a file.
SendCommand("RE ST ", _FileOffset)
If (_ResponseCode <> 350) Then
'The FTP host does not support resuming.
_FileOffset = 0
End If
End If
If (_FileOffset <> 0) Then
_FTPFileStreamO utput.Seek(_Fil eOffset,
SeekOrigin.Begi n)
End If
End If

'Send an FTP RETR command to retrieve a file.
SendCommand("RE TR ", fileName)

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If _FTPDataSocket. Connected Then
While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPDataSocket. Receive(_Buffer ,
_Buffer.Length, 0)
_FTPFileStreamO utput.Write(_Bu ffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While
Else
_ResponseData = "FTP data socket failed to connect."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - GetFile subroutine failed - FTP data socket
failed to connect.", "")
End If

_FTPFileStreamO utput.Close()

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

End Sub

'''<summary>
''' Public Sub: UploadFile - This subroutine uploads a specific
file to an FTP host.
'''<param name="fileName" >As String</param>
'''<param name="filePath" >As String</param>
'''<optional param name="fileResum e">As Boolean</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub UploadFile(ByVa l fileName As String, ByVal filePath As
String, Optional ByVal fileResume As Boolean = False)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Set the FTP mode to binary.
SetBinaryMode(T rue)

' Create an FTP data socket.
Dim _FTPDataSocket As Socket = CreateDataSocke t()

' Check to see if the file exists locally before the upload.
If (File.Exists(fi lePath & fileName)) Then

' Open the input stream to read the source file.
Dim _FTPFileStreamI nput As FileStream
_FTPFileStreamI nput = New FileStream(file Path & fileName,
FileMode.Open)

If fileResume Then
' Check to see if part of the file has already been
uploaded.
Dim _FileOffset As Long
_FileOffset = 0

Try
_FileOffset = GetFileSize(fil eName)
Catch ex As Exception
_FileOffset = 0
End Try

If (_FileOffset > 0) Then
' Send an FTP REST command to restart a file.
SendCommand("RE ST ", _FileOffset)
If (_ResponseCode <> 350) Then
'The FTP host does not support resuming.
_FileOffset = 0
End If
End If

If (_FileOffset <> 0) Then
_FTPFileStreamI nput.Seek(_File Offset,
SeekOrigin.Begi n)
End If
End If

' Send an FTP STOR command to store a file.
SendCommand("ST OR ", fileName)

' Upload the file.
Const _BufferSize As Integer = 512
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

_BytesRead = _FTPFileStreamI nput.Read(_Buff er, 0,
_Buffer.Length)
If _FTPDataSocket. Connected Then
While (_BytesRead > 0)
_FTPDataSocket. Send(_Buffer, _BytesRead, 0)
_BytesRead = _FTPFileStreamI nput.Read(_Buff er, 0,
_Buffer.Length)
End While

Else
_ResponseData = "FTP data socket failed to
connect."
' Throw New
MPException(App Settings.Item(" Project"), "MP.IT.Web.Libr ary.FTP -
UploadFile subroutine failed - FTP data socket failed to connect.", "")
End If
_FTPFileStreamI nput.Close()

Else
_ResponseData = "File to upload does not exist on local
machine."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - UploadFile subroutine failed - file to upload
does not exist on local machine.", "")
End If

' Close and destroy the FTP data socket.
If (_FTPDataSocket Is Nothing = False) Then
_FTPDataSocket. Close()
_FTPDataSocket = Nothing
End If

End Sub

'''<summary>
''' Public Sub: UploadFile - This subroutine deletes a specific
file on an FTP host.
'''<param name="fileName" >As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub DeleteFile(ByVa l fileName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Send an FTP DELE command to delete a file.
SendCommand("DE LE ", fileName)

End Sub

'''<summary>
''' Public Sub: RenameFile - This subroutine renames a specific
file on an FTP host.
'''<param name="fileName" >As String</param>
'''<param name="fileNewNa me">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub RenameFile(ByVa l fileName As String, ByVal fileNewName
As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

' Send an FTP RNFR command to select a file to be renamed.
SendCommand("RN FR ", fileName)

'Send an FTP RNTO command to rename the selected file to a new
file name.
SendCommand("RN TO ", fileNewName)

End Sub

'''<summary>
''' Public Sub: GetDirectory - This subroutine gets the current
directory on an FTP host.
'''<returns>Sub routine returns nothing.</returns>
Public Sub GetDirectory()

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP CWD command to change to a directory.
SendCommand("PW D ", "")

End Sub

'''<summary>
''' Public Sub: ChangeDirectory - This subroutine changes to a
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub ChangeDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Check if in the root directory.
If (directoryName. Equals(".")) Then
Exit Sub
End If

'Send an FTP CWD command to change to a directory.
SendCommand("CW D ", directoryName)

End Sub

'''<summary>
''' Public Sub: CreateDirectory - This subroutine creates a new
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub CreateDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP MKD command to make a new directory.
SendCommand("MK D ", directoryName)

End Sub

'''<summary>
''' Public Sub: RemoveDirectory - This subroutine removes a
directory on an FTP host.
'''<param name="directory Name">As String</param>
'''<returns>Sub routine returns nothing.</returns>
Public Sub RemoveDirectory (ByVal directoryName As String)

' Check to see if user is logged into FTP host.
If Not _FTPLogin Then
Login()
End If

'Send an FTP RMD command to remove a directory.
SendCommand("RM D ", directoryName)

End Sub

#End Region

#Region "Private Methods"

'''<summary>
''' Private Sub: CreateCommandSo cket - Provided a Host and a port
this subroutine will instantiate an FTP command socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Private Sub CreateCommandSo cket()

' Create the FTP command socket.
_FTPCommandSock et = New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)

Try
Dim HostMachine As IPEndPoint = New
IPEndPoint(Dns. Resolve(_Host). AddressList(0), _Port)
Try
' Connect the FTP command socket to the FTP host
machine.
_FTPCommandSock et.Connect(Host Machine)
Catch ex As Exception
' Connection could not be opened due to malformed
connection.
_ResponseData = "FTP Command Socket Connection Could
Not Be Established."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Command Socket Connection Could Not Be
Established.", ex)
End Try
Catch ex As Exception
' Connection could not be opened because DNS cannot resolve
the host IP.
_ResponseData = "FTP Command Socket Connection Could Not Be
Established. Connection could not be opened because DNS cannot resolve
the host IP."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Command Socket Connection Could Not Be
Established. DNS cannot resolve the FTP host.", ex)
End Try
_ResponseData = "FTP Command Socket Connection Established."
ReadResponse()

End Sub

'''<summary>
''' Private Function: CreateDataSocke t - Provided that a PASV
command has been sent to the host, this function returns
''' an FTP data socket.
'''</summary>
'''<returns>Sub routine returns nothing.</returns>
Private Function CreateDataSocke t() As Socket

Dim _FTPDataSocket As Socket
Dim _FTPHostIPFront Bracket As Integer
Dim _FTPHostIPBackB racket As Integer
Dim _FTPHostIPData As String
Dim _FTPHostIPLengt h As Integer
Dim _FTPHostIPPartC ount As Integer
Dim _FTPHostIPParts (6) As Integer
Dim _FTPHostIPChara ter As Char
Dim _Buffer As String
Dim _Counter As Integer

'Send an FTP PASV command to use passive data connection.
SendCommand("PA SV", "")

_FTPHostIPFront Bracket = _ResponseData.I ndexOf("(")
_FTPHostIPBackB racket = _ResponseData.I ndexOf(")")
_FTPHostIPData = _ResponseData.S ubstring(_FTPHo stIPFrontBracke t
+ 1, _FTPHostIPBackB racket - _FTPHostIPFront Bracket - 1)

_FTPHostIPLengt h = _FTPHostIPData. Length
_FTPHostIPPartC ount = 0
_Buffer = ""

For _Counter = 0 To ((_FTPHostIPLen gth - 1) And
_FTPHostIPPartC ount <= 6)
_FTPHostIPChara ter =
Char.Parse(_FTP HostIPData.Subs tring(_Counter, 1))
If (Char.IsDigit(_ FTPHostIPCharat er)) Then
_Buffer += _FTPHostIPChara ter
ElseIf (_FTPHostIPChar ater <> ",") Then
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Host did not accept the PASV command.",
"")
End If

If ((_FTPHostIPCha rater = ",") Or (_Counter + 1 =
_FTPHostIPLengt h)) Then
Try
_FTPHostIPParts (_FTPHostIPPart Count) =
Int32.Parse(_Bu ffer)
_FTPHostIPPartC ount += 1
_Buffer = ""
Catch ex As Exception
' Throw New
MPException(App Settings.Item(" Project"), "MP.IT.Web.Libr ary.FTP - FTP
Host did not accept the PASV command.", ex)
End Try
End If
Next

' Create the data host.
Dim _DataHost As String = _FTPHostIPParts (0) & "." &
_FTPHostIPParts (1) & "." & _FTPHostIPParts (2) & "." &
_FTPHostIPParts (3)

' Create the data port.
Dim _DataPort As Integer = _FTPHostIPParts (4) << 8

' Determine the data port number.
_DataPort = _DataPort + _FTPHostIPParts (5)

' Create the FTP data socket from the data host and data port.
_FTPDataSocket = New Socket(AddressF amily.InterNetw ork,
SocketType.Stre am, ProtocolType.Tc p)

Try
Dim HostMachine As IPEndPoint = New
IPEndPoint(Dns. Resolve(_DataHo st).AddressList (0), _DataPort)
Try
' Connect the FTP data socket to the FTP host machine.
_FTPDataSocket. Connect(HostMac hine)
Return _FTPDataSocket
Catch ex As Exception
' Connection could not be opened due to malformed
connection.
_ResponseData = "FTP Data Socket Connection Could Not
Be Established."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Data Socket Connection Could Not Be
Established.", ex)
End Try
Catch ex As Exception
' Connection could not be opened because DNS cannot resolve
the host IP.
_ResponseData = "FTP Data Socket Connection Could Not Be
Established. Connection could not be opened because DNS cannot resolve
the host IP."
' Throw New MPException(App Settings.Item(" Project"),
"MP.IT.Web.Libr ary.FTP - FTP Data Socket Connection Could Not Be
Established. DNS cannot resolve the FTP host.", ex)
End Try
_ResponseData = "FTP Data Socket Connection Established."

End Function

'''<summary>
''' Private Sub: ReadResponse - This subroutine will read line by
line the reply to
''' a command sent to an FTP host.
'''</summary>
'''<returns>Fun ction returns a string.</returns>
Private Sub ReadResponse()

' Read the response from the FTP host.
_ResponseData = ReadLine(False)
_ResponseCode = Int32.Parse(_Re sponseData.Subs tring(0, 3))

End Sub

'''<summary>
''' Private Function: ReadLine - This function handles the actual
reading of the FTP host reply.
'''</summary>
'''<param name="clearResp onse">As Boolean</param>
'''<returns>Fun ction returns a string.</returns>
Private Function ReadLine(ByVal clearResponse As Boolean) As String

Const _EndLine As Char = "\n"
Const _BufferSize As Integer = 512

Dim _Data As String = ""
Dim _Buffer(_Buffer Size) As Byte
Dim _BytesRead As Integer = 0

If (clearResponse = True) Then _ResponseData = String.Empty

While (True)
Array.Clear(_Bu ffer, 0, _BufferSize)
_BytesRead = _FTPCommandSock et.Receive(_Buf fer,
_Buffer.Length, 0)
_Data += ASCII.GetString (_Buffer, 0, _BytesRead)

If (_BytesRead < _Buffer.Length) Then Exit While
End While

Dim _Parts() As String = _Data.Split(_En dLine)

If (_Parts.Length > 2) Then
_ResponseData = _Parts(_Parts.L ength - 2)
Else
_ResponseData = _Parts(0)
End If

If (_ResponseData. Substring(3, 1).Equals(" ") = False) Then
Return ReadLine(False)
End If

Return _ResponseData
End Function

#End Region

End Class

Mar 23 '06 #8
Tom,
Is there a reason you are implementing this code when there are free
and working ftp clients available for .NET (Indy project comes to
mind)? If this is for personal learning I will be glad to look over
this code, but it might take a little debugging time :)

At least it is a standard dotNet part now, so there is in my opinion nothing
wrong with learning that.

http://msdn2.microsoft.com/en-us/lib...18(VS.80).aspx

Just my thought,

Cor
Mar 23 '06 #9
Tom,

I figured out my issue 2 seconds before you got your post up. Anyways
everything works great now for Windows and Unix, however now my problem
is timeouts. When I actually went to use it on a Unix server I hit a
snag doing an NLST command as there are some 30,000 files to read thru.
Needless to say my code doesnt make it thru because FTP servers have
timeouts that basically say that if it doesn't get a reply back within
a given time period to close the command connection socket. Now I
tested this theory using two third party apps such as FileZilla and WS
FTP Pro and both of these apps also got timeout errors. So does anyone
know who to change the FTP timeout setting once telnetted into the Unix
box?

Mar 24 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
2883
by: Justin Lazanowski | last post by:
Cross posting this question on the recommendation of an I have a .NET application that I am developing in C# I am loading information in from a dataset, and then pushing the dataset to a grid, or other controls depending on the particular form. This application is setup with one MDI parent calling MDI children with the exception of one Modal form (the report viewer). When I run the application and run one of the screens that pulls...
1
1454
by: Bill Soudan | last post by:
Hi all, I'm a MS/.NET newbie, diving right into CLR interop. I've worked through the various issues foreign to me as a UNIX guy: multiple heap issues because I was linking to different CRT instances (ugh), calling conventions, marshalling, etc. I'm stumped on one issue, though. Quick structural overview: straight C dll wrapped by C# wrapper class. C# wrapper provides the implementation for a number of function callbacks via...
7
1847
by: David Laub | last post by:
I have stumbled across various Netscape issues, none of which appear to be solvable by tweaking the clientTarget or targetSchema properties. At this point, I'm not even interested in "solving" these problems - I'm more interested in isolating them, .i.e. finding a "complete" list of issues. Here's my list of serious issues found so far. By serious, I mean functionality that fails, as opposed to much less serious (albeit annoying) display...
3
5081
by: Michael Hoehne | last post by:
Hi, I'm currently facing a problem with a mixed environment using .NET 1.1 and ..NET 2.0 web services. We have a client application (the "client", system 1) running on .NET 2.0/WinXP, calling our web service (The "Web Service Server") running on a separate machine (also .NET 2.0, Win2003 Server, system 2). The web service server (system 2) itself makes calls to methods in the CRM
10
3081
by: Robert | last post by:
I have an app that was originally 1.1, now migrated to 2.0 and have run into some sporadic viewstate errors...usually saying the viewstate is invalid, eventvalidation failed or mac error. My web config does specify a machinekey setting: <machineKey validationKey="447C05E8B3A71401CC4CAE5513A7F1A3494A3618EE819316AAD1D58433F236A759D66FB4154500E01EB4E1BC1DE42046E2D652D391CB8367A1649438867A02EB"...
15
2571
by: Pucca | last post by:
I'm getting an error when I tried to use this BerConverter class in my C# code. Even though the Interent doc says that it runs on Win2000 sp4, I just thgouth I'll double check. Does anyone know if BerConverter is supported for Win2000 server? http://msdn2.microsoft.com/en-us/library/system.directoryservices.protocols.berconverter.decode.aspx -- Thanks.
62
5055
by: Tony Ciconte | last post by:
I have a rather complex commercial Acc2003 application (tab controls, 50K+ lines of VBA code, etc.) that will not run well at all on Windows Vista Ultimate. I have seen posts indicating that Acc2003 MDBs should work on Vista. However, our particular file has too many problems to be viable on a Vista platform. Even converting it to an Acc2007 accdb file has no positive effect. I realize that Vista is new and should be avoided like the...
6
4012
by: Bradley Plett | last post by:
I have run into this problem occasionally, and have crude ways of getting around it, but I'm wondering if anyone else has a better, more elegant solution. I have a web service and a client application that share a class. For one of my web service methods, for example, I return an object of the given class type. However, when I try to cast the object in my client, I run into a namespace conflict. This makes sense to me, but if I...
1
1618
by: mattl52 | last post by:
I am having a problem doing callbacks using an RMI connection. We have two servers. One exists on one domain on a windows box. The other server is a unix box that exists on a separate domain behind a router performing NAT. We connect to the Unix box using the external IP of the router. However, we receive an error on the callback from the interal IP of the Unix box. It says that the Unix box is a non-local host. Java policy forbids...
0
8647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9132
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8864
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7682
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6506
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2288
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1986
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.