Introduction
Imagine a life without the Internet. You can’t, can you? No. Just today, I told one of my colleagues that the human race has grown so dependent on the Internet, and when, for example, a network is down, you cannot do any work. The Internet is good, but it is very scary to come to a realization of our need for the Internet. Today, I will quickly show you how to create an FTP program in Visual Basic.
Let’s get technical—but not too much!
In an earlier article, I spoke about UDP and Visual Basic. In this article, I spoke about all the protocols that make the Internet what it is. That just covered the communication part; let’s explore the real Internet now.
The Internet
The Internet is a global system of interconnected computer networks that use TCP/IP to link trillions of devices worldwide linked by an array of electronic, wireless, and optical networking technologies. Okay, Captain Obvious (that’s me), let’s move on!
For a good and proper lesson on the Internet and its origins, this Wikipedia article will be helpful.
I am just going to highlight Protocols and specifically the FTP Protocol here.
Protocols
A Protocol, or rather a Communication Protocol, is a set of rules that enables two or more entities to transmit information to one another.
Common Protocols
Some of the most common Protocols are as follows:
- TCP
- IP
- UDP
- POP
- SMTP
- HTTP
- FTP
For more information regarding these protocols, read through this article of mine.
FTP
FTP (File Transfer Protocol) is used for exchanging files over the Internet.
Our Program
Start Visual Basic and create a Visual Basic Windows Forms application. Add four buttons to your form. I have not named any of my objects. Design your form to look more or less like Figure 1.
Figure 1: Our Design
The Code
You can most likely already deduce that we will cover four FTP operations today. These are:
- Uploading a file to an FTP Server
- Downloading a file from an FTP Server
- Deleting a file from an FTP Server
- Renaming a file on an FTP Server
Before we can do any of those, we need to import the necessary namespaces into our project. Add them now:
Imports System.Net 'Web Imports System.IO 'Files
The System.Net namespace enables you to work with Internet protocols, Internet Web pages, and Internet resources.
The System.IO namespace enables you to work with any file.
Uploading a File to an FTP Server
Add the following code behind the button Labeled ‘UPLOAD’:
'Upload File to FTP site Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles Button1.Click 'Create Request To Upload File' Dim wrUpload As FtpWebRequest = DirectCast(WebRequest.Create _ ("ftp://ftp.test.com/file.txt"), FtpWebRequest) 'Specify Username & Password' wrUpload.Credentials = New NetworkCredential("user", _ "password") 'Start Upload Process' wrUpload.Method = WebRequestMethods.Ftp.UploadFile 'Locate File And Store It In Byte Array' Dim btfile() As Byte = File.ReadAllBytes("c:\file.txt") 'Get File' Dim strFile As Stream = wrUpload.GetRequestStream() 'Upload Each Byte' strFile.Write(btfile, 0, btfile.Length) 'Close' strFile.Close() 'Free Memory' strFile.Dispose() End Sub
First up, an FtpWebRequest object gets created. This object will be responsible for sending the specific FTP commands to either identify the user or do a certain function, such as uploading a file. In a Credentials request, I sent through a username and password that were made up (in my case, as this is just an example). I then specified that I want to upload a file. The File stream is then read and sent byte by byte until the Upload is complete. Easy, peasy.
The rest of the code will have a lot of similarities. Obviously, there are more advanced ways of doing this, but this article exists to help you get the basics right as well as familiarize yourself with FTP.
Add the following code:
'Download A File From FTP Site' Private Sub Button2_Click(sender As Object, e As EventArgs) _ Handles Button2.Click 'Create Request To Download File' Dim wrDownload As FtpWebRequest = _ WebRequest.Create("ftp://ftp.test.com/file.txt") 'Specify That You Want To Download A File' wrDownload.Method = WebRequestMethods.Ftp.DownloadFile 'Specify Username & Password' wrDownload.Credentials = New NetworkCredential("user", _ "password") 'Response Object' Dim rDownloadResponse As FtpWebResponse = _ wrDownload.GetResponse() 'Incoming File Stream' Dim strFileStream As Stream = _ rDownloadResponse.GetResponseStream() 'Read File Stream Data' Dim srFile As StreamReader = New StreamReader(strFileStream) Console.WriteLine(srFile.ReadToEnd()) 'Show Status Of Download' Console.WriteLine("Download Complete, status {0}", _ rDownloadResponse.StatusDescription) srFile.Close() 'Close rDownloadResponse.Close() End Sub 'Delete File On FTP Server' Private Sub Button3_Click(sender As Object, e As EventArgs) _ Handles Button3.Click 'Create Request To Delete File' Dim wrDelete As FtpWebRequest = _ CType(WebRequest.Create("ftp://ftp.test.com/file.txt"), _ FtpWebRequest) 'Specify That You Want To Delete A File' wrDelete.Method = WebRequestMethods.Ftp.DeleteFile 'Response Object' Dim rDeleteResponse As FtpWebResponse = _ CType(wrDelete.GetResponse(), _ FtpWebResponse) 'Show Status Of Delete' Console.WriteLine("Delete status: {0}", _ rDeleteResponse.StatusDescription) 'Close' rDeleteResponse.Close() End Sub
As I mentioned, there are a lot of similarities between the previous code and these two pieces. Button 2 downloads a file from FTP. Button 3 deletes a file from an FTP location, all using the same techniques I demonstrated earlier with uploading a file.
Add the last bit of code:
'rename File On FTP Server' Private Sub Button4_Click(sender As Object, e As EventArgs) _ Handles Button4.Click 'Create Request To Rename File' Dim wrRename As System.Net.FtpWebRequest = _ CType(FtpWebRequest.Create("ftp://ftp.test.com/file.txt"), _ FtpWebRequest) 'Specify Username & Password' wrRename.Credentials = New NetworkCredential("user", _ "password") 'Rename A File' wrRename.Method = WebRequestMethods.Ftp.Rename wrRename.RenameTo() = "TEST.TXT" 'Determine Response Of Operation' Dim rResponse As System.Net.FtpWebResponse Try rResponse = CType(wrRename.GetResponse, FtpWebResponse) 'Get Description' Dim strStatusDesc As String = rResponse.StatusDescription 'Get Code' Dim strStatusCode As FtpStatusCode = rResponse.StatusCode If strStatusCode <> Net.FtpStatusCode.FileActionOK Then MessageBox.Show("Rename failed. Returned status = _ " & strStatusCode & " " & strStatusDesc) Else MessageBox.Show("Rename succeeded") End If Catch ex As Exception MessageBox.Show("Rename failed. " & ex.Message) End Try End Sub
The preceding code renames a file at an FTP location. I also introduced the FtpWebResponse class that assists in giving feedback to operations. In this case, I tested the response and, if an error is returned, I will know that there is something wrong.
Conclusion
Knowing when and how to work with the Internet’s many different protocols is essential in any decent application.