This is another shocking lack of .NET - easy FTP. While version 2.0 of .NET does in fact have native FTP handling capabilities (WinHTTP), it is for a lack of a better word, a pain - especially when you are trying something simple. If you are building a commercially distributed, mission-critical, or enterprise class application, you probably will find it valuable to go through the extra steps to use native functionality. However, if FTP is a relatively quick need, this has my recommendation.
I searched high and low for an easy way to do this. There are plenty of complex methods, controls available for sale, and outdated methods to accomplish a simple FTP download. The simplest way to do so (and have it working by lunchtime) is to use the edtFTPnet control available at http://www.enterprisedt.com/products/edtftpnet/overview.html. It is free for commercial use under a GPL license. My code sample as below:
First, add the control to your toolbox.
Second, drag the control onto the applicable form.
Third, your code must specify connection characteristics. Sample below:
NOTE: I am referencing My.Settings where the data is stored in the application - you can easily use direct references or assign variables to control the data. Also, I have a setting in My.Settings for ACTIVE or PASSIVE file transfer mode.
FTPConnection1 is the control name.
You can also set these settings directly in the control properties.
'load FTP settings
FtpConnection1.ServerAddress = My.Settings.FTPServer
FtpConnection1.UserName = My.Settings.FTPUsername
FtpConnection1.Password = My.Settings.FTPPassword
FtpConnection1.ServerPort = CInt(My.Settings.FTPPort)
FtpConnection1.ServerDirectory = My.Settings.FTPDirectory
If My.Settings.FTPConnectionMode = "1" Then
FtpConnection1.ConnectMode = EnterpriseDT.Net.Ftp.FTPConnectMode.ACTIVE
Else
FtpConnection1.ConnectMode = EnterpriseDT.Net.Ftp.FTPConnectMode.PASV
End If
Fourth, the connection and file download code.
FtpConnection1.Connect()
FtpConnection1.ChangeWorkingDirectory("Insert FTP path here")
FtpConnection1.DownloadFile("Insert Where file is going on PC", "Insert File Name on FTP Server")
FtpConnection1.Close()
That's it.
Thursday, July 24, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment