Visual Basic .NET - FTP Uploading
File Transfer Protocol (FTP) is a stable platform for interaction with dynamic content (ticker news, image of the day etc.) and communication with the end-user. Using FTP in VB.Net is dead easy, simply copy the code and replace the strings with the configuration for your FTP account.
Public Sub FTPUpload(ByVal FTPName As String, ByVal LocalCopy As String)
Try
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(”ftp://yoursite.com/” & FTPName), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential(”Username”, “Password”)
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
‘ read in file…
Dim bFile() As Byte = System.IO.File.ReadAllBytes(LocalCopy)
‘ upload file…
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Dispose()
clsStream.Close()
Catch ex As Exception
End Try
End Sub
Then call this Sub through an event:
Private Sub TNetwork_frm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FTPUpload(”Info.txt”, “C:\MyDocuments\Info.txt”)
FTPUpload(”Stats.txt”, “C:\MyDocuments\Stats.txt”)
End Sub
This snippet is for uploading files, however, you will need to save a local copy of the file to your hard drive before this can be done. Firstly, specify the target location on your site, i.e, “File.txt” or “images/Image.jpg”. For the second parameter, point to the copy of the file on the local HD, so: “C:\File.txt” or “C:\MyPictures\Image.jpg”.
FTP transfers can last anywhere between 0.1s and several hours depending largely on the quantity and size of the files. By default, any pre-existing file is overwritten, although there doesn’t need to be a file to exist for you to upload it.
Though FTP is a useful solution and a considerably simpler alternative to other file storage methods, many hosting configurations limit the amount of FTP users at any one time to about 2 or 3. Meaning that implementation in programs that are to have extensive userbases should be avoided unless you can afford to upgrade to larger FTP user capacities.