Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse FTP to upload and download files in Visual Basic 2005
DescriptionThis example shows how to use FTP to upload and download files in Visual Basic 2005.
KeywordsFTP, upload, download, transfer, transfer files, VB 2005
CategoriesVB.NET, Internet
 
The FtpFile subroutine transfers a file from one URI to another. It first opens a FileStream to use in writing into the destination file.

It then creates a FileWebRequest object referring to the source file's URI. It makes a NetworkCredential object with the user's name and password (for anonymous FTP, set the user name to "Anonymous" and the password to your email address). The code then get's the FTP server's response and response stream.

Next the code reads bytes from the source file and copies them into the destination stream until the whole file has been copied. It finishes by closing the streams.

 
' Use FTP to transfer a file.
Private Sub FtpFile(ByVal from_uri As String, ByVal to_uri _
    As String, ByVal user_name As String, ByVal password As _
    String)
    ' Open a FileStream to hold the new file.
    Dim fs_to As New FileStream( _
        to_uri, FileMode.Create)

    ' Connect to the FTP server.
    Dim request As FileWebRequest = _
        FtpWebRequest.Create(from_uri)

    ' Fill in the user name and password.
    request.Method = WebRequestMethods.Ftp.DownloadFile
    request.Credentials = New NetworkCredential( _
        user_name, password)

    ' Get the response and response stream.
    Dim response As WebResponse = request.GetResponse
    Dim response_stream As Stream = _
        response.GetResponseStream

    ' Read the result file.
    Dim buffer(1024) As Byte
    Dim total_bytes As Long = 0
    Dim bytes_read As Integer = _
        response_stream.Read(buffer, 0, buffer.Length)
    While bytes_read > 0
        total_bytes += bytes_read
        fs_to.Write(buffer, 0, bytes_read)
        bytes_read = response_stream.Read(buffer, 0, 1024)
    End While

    ' Close the streams.
    fs_to.Close()
    response_stream.Close()

    Debug.WriteLine("FtpFile transfered " & _
        total_bytes.ToString() & " bytes")
End Sub
 
Note that my network setup has prevented me from testing this example as much as I would like. Let me know if you find problems with it.
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated