Upload file to FTP site using VB.NET

后端 未结 6 1596
夕颜
夕颜 2020-12-09 11:25

I have this working code from this link, to upload a file to an ftp site:

\' set up request...
Dim clsRequest As System.Net.FtpWebRequest = _
    DirectCast(         


        
6条回答
  •  天涯浪人
    2020-12-09 12:22

    Yes, FTP protocol overwrites existing files on upload.


    Note that there are better ways to implement the upload.

    The most trivial way to upload a binary file to an FTP server using .NET framework is using WebClient.UploadFile:

    Dim client As WebClient = New WebClient
    client.Credentials = New NetworkCredential("username", "password")
    client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")
    

    If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, etc), use FtpWebRequest. Easy way is to just copy a FileStream to FTP stream using Stream.CopyTo:

    Dim request As FtpWebRequest =
        WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
    request.Credentials = New NetworkCredential("username", "password")
    request.Method = WebRequestMethods.Ftp.UploadFile
    
    Using fileStream As Stream = File.OpenRead("C:\local\path\file.zip"),
          ftpStream As Stream = request.GetRequestStream()
        fileStream.CopyTo(ftpStream)
    End Using
    

    If you need to monitor an upload progress, you have to copy the contents by chunks yourself:

    Dim request As FtpWebRequest =
        WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip")
    request.Credentials = New NetworkCredential("username", "password")
    request.Method = WebRequestMethods.Ftp.UploadFile
    
    Using fileStream As Stream = File.OpenRead("C:\local\path\file.zip"),
          ftpStream As Stream = request.GetRequestStream()
        Dim read As Integer
        Do
            Dim buffer() As Byte = New Byte(10240) {}
            read = fileStream.Read(buffer, 0, buffer.Length)
            If read > 0 Then
                ftpStream.Write(buffer, 0, read)
                Console.WriteLine("Uploaded {0} bytes", fileStream.Position)
            End If
        Loop While read > 0
    End Using
    

    For GUI progress (WinForms ProgressBar), see C# example at:
    How can we show progress bar for upload with FtpWebRequest

    If you want to upload all files from a folder, see C# example at
    Upload directory of files using WebClient.

提交回复
热议问题