简体   繁体   中英

VB.NET FTP File Download

I'm trying to set up my program to connect to my FTP and download files directly from my server. This what I have so far. I don't know what I'm doing wrong, or where I'm going wrong, because no matter how I code it either says "End Expected" or "Method can't handle etc due to signatures not being compatible"

I don't know what I'm doing wrong, any help would be greatly appreciated.

 Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click

(ByVal downloadpath As String, ByVal ftpuri As String, ByVal ftpusername As String, ByVal ftppassword As String)

    'Create a WebClient.
    Dim request As New WebClient()

    ' Confirm the Network credentials based on the user name and password passed in.
    request.Credentials = New Net.NetworkCredential("Username", "Password")

    'Read the file data into a Byte array
    Dim bytes() As Byte = request.DownloadData("ftp://ftp.yourwebsitename/file.extension")

    Try
        '  Create a FileStream to read the file into
        Dim DownloadStream As FileStream = IO.File.Create("C:\Local\Test.zip")
        '  Stream this data into the file
        DownloadStream.Write(bytes, 0, bytes.Length)
        '  Close the FileStream
        DownloadStream.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

    MessageBox.Show("Process Complete")

End Sub

You probably pasted an existing method inside a Button.Click handler by mistake.
Rebuilding what was probably the original method is almost enough.

Note that this FTP procedure is a quite basic . You can rely on it only when downloading from a known remote resource. Also, as it it, it doesn't allow to show the download progress or even to cancel it.

Maybe take a look at the WebClient.DownloadDataAsync method, which allows to easily implement a progress bar and cancel the download procedure, when needed.

Also, if you're interested, in this SO question , you can find some notes and a sample Form, which can be included in a Project, to test some features of the FtpWebRequest .

Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
    Button16.Enabled = False
    DownloadFile("C:\Local\Test.zip", "ftp://ftp.example.com/file.ext", "[username]", "[password]")
    Button16.Enabled = True
End Sub

Private Sub DownloadFile(destinationPath As String, ftpResource As String, ftpUsername As String, ftpPassword As String)

    Dim client As New WebClient()
    client.Credentials = New NetworkCredential(ftpUsername, ftpPassword)

    Try
        Dim dataBytes() As Byte = client.DownloadData(ftpResource)

        If dataBytes.Length > 0 Then
            File.WriteAllBytes(destinationPath, dataBytes)
            MessageBox.Show("Download Complete")
        Else
            MessageBox.Show("Download failed")
        End If

    Catch ex As WebException
        MessageBox.Show(ex.Message)
    Catch ex As IoException
        MessageBox.Show(ex.Message)
    End Try
End Sub

Here is a Console solution. Compile this into a exe file, and run it by double-clicking the executable or get a scheduler (ie, Windos Task Scheduler) to open and run the file (it runs as soon as it opens).

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Linq
Imports System.Text
Imports System.Net
Imports System.IO

Namespace ConsoleApplication1

    Class Program

        Private Shared Sub Main(ParamArray ByVal args() As String)
            If args.Any Then
                ' Do code that references args
                Dim dt As DateTime = DateTime.Today.AddDays(-1)
                Dim date As String = String.Format("{0:yyyyMMdd}", dt)
                Dim p As Program = New Program
                p.getFTPFile(("raw_CA_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
                p.getFTPFile(("raw_EM_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
                p.getFTPFile(("raw_GLB_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
                p.getFTPFile(("raw_US_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
            Else
                ' Do code that depends on no input arguments.
                Dim dt As DateTime = DateTime.Today.AddDays(-1)
                Dim date As String = String.Format("{0:yyyyMMdd}", dt)
                Dim p As Program = New Program
                p.getFTPFile(("raw_CA_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
                p.getFTPFile(("raw_EM_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
                p.getFTPFile(("raw_GLB_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
                p.getFTPFile(("raw_US_"  _
                                + (date + ".txt")))
                ' match a certain pattern in the name of the file
            End If

        End Sub

        Private Sub getFTPFile(ByVal FTPFile As String)
            FTPSettings.IP = "000.000.100.000"
            FTPSettings.UserID = "your_id"
            FTPSettings.Password = "your_password"
            Dim reqFTP As FtpWebRequest = Nothing
            Dim ftpStream As Stream = Nothing
            Try 
                Dim outputStream As FileStream = New FileStream(("C:\Downloads\AFL_Files\" + FTPFile), FileMode.Create)
                reqFTP = CType(FtpWebRequest.Create(("ftp://something@ftp.corp.com/your_path/" + FTPFile)),FtpWebRequest)
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
                reqFTP.UseBinary = true
                reqFTP.Credentials = New NetworkCredential(FTPSettings.UserID, FTPSettings.Password)
                Dim response As FtpWebResponse = CType(reqFTP.GetResponse,FtpWebResponse)
                ftpStream = response.GetResponseStream
                Dim cl As Long = response.ContentLength
                Dim bufferSize As Integer = 2048
                Dim readCount As Integer
                Dim buffer() As Byte = New Byte((bufferSize) - 1) {}
                readCount = ftpStream.Read(buffer, 0, bufferSize)

                While (readCount > 0)
                    outputStream.Write(buffer, 0, readCount)
                    readCount = ftpStream.Read(buffer, 0, bufferSize)

                End While

                ftpStream.Close
                outputStream.Close
                response.Close
            Catch ex As Exception
                If (Not (ftpStream) Is Nothing) Then
                    ftpStream.Close
                    ftpStream.Dispose
                End If

                Throw New Exception(ex.Message.ToString)
            End Try

        End Sub

        Public Class FTPSettings

            Public Shared Property IP As String
                Get
                End Get
                Set
                End Set
            End Property

            Public Shared Property UserID As String
                Get
                End Get
                Set
                End Set
            End Property

            Public Shared Property Password As String
                Get
                End Get
                Set
                End Set
            End Property
        End Class
    End Class
End Namespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM