Upload file to FTP site using VB.NET

2020-02-05 03:49发布

问题:

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(System.Net.WebRequest.Create("ftp://ftp.myserver.com/test.txt"), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("myusername", "mypassword")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes("C:\Temp\test.txt")

' upload file...
Dim clsStream As System.IO.Stream = _
    clsRequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()

I wonder, if the file already exists in the ftp directory, the file will be overwritten?

回答1:

Looking at the MSDN documentation this maps to the FTP STOR command. Looking at the definition for the FTP STOR command it will overwrite existing files, if the user has permissions.

So in this case, yes the file would be overwritten.



回答2:

From: Link

STOR (STORE)

STOR

This command causes the FTP server to accept the data transferred via the data connection and to store the data as a file at the FTP server. If the file specified in pathname exists at the server site, then its contents shall be replaced by the data being transferred. A new file is created at the FTP server if the file specified in pathname does not already exist.



回答3:

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.



回答4:

It is important to know that, Files are just references to pointers that point to an array of bytes in memory.

When a file writing operation is asked to write a file to a pointer, it will not check if the file exist; Simply, the file system will allow the operation to continue unless the bytes in memory are being used (although you can force overwrite).

If you want to check if a file exist before writing the file use my GetDirectory method in VB.net here: https://stackoverflow.com/a/28664731/2701974



回答5:

Use This Function to Upload file

Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)

Dim _FileInfo As New System.IO.FileInfo(_FileName)

' Create FtpWebRequest object from the Uri provided
Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)

' Provide the WebPermission Credintials
_FtpWebRequest.Credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)

' By default KeepAlive is true, where the control connection is not closed
' after a command is executed.
_FtpWebRequest.KeepAlive = False

' set timeout for 20 seconds
_FtpWebRequest.Timeout = 20000

' Specify the command to be executed.
_FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

' Specify the data transfer type.
_FtpWebRequest.UseBinary = True

' Notify the server about the size of the uploaded file
_FtpWebRequest.ContentLength = _FileInfo.Length

' The buffer size is set to 2kb
Dim buffLength As Integer = 2048
Dim buff(buffLength - 1) As Byte

' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()

Try
    ' Stream to which the file to be upload is written
    Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()

    ' Read from the file stream 2kb at a time
    Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)

    ' Till Stream content ends
    Do While contentLen <> 0
        ' Write Content from the file stream to the FTP Upload Stream
        _Stream.Write(buff, 0, contentLen)
        contentLen = _FileStream.Read(buff, 0, buffLength)
    Loop

    ' Close the file stream and the Request Stream
    _Stream.Close()
    _Stream.Dispose()
    _FileStream.Close()
    _FileStream.Dispose()
Catch ex As Exception
    MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub

HOW TO USE:

' Upload file using FTP UploadFile("c:\UploadFile.doc", "ftp://FTPHostName/UploadPath/UploadFile.doc", "UserName", "Password")



回答6:

this is working code to upload files to a FTP server

               Dim request As FtpWebRequest = DirectCast(WebRequest.Create(New Uri("ftp://" & server & "/" & folderName & "/" & filename)), System.Net.FtpWebRequest)
                        request.Method = WebRequestMethods.Ftp.UploadFile
                        request.Credentials = New NetworkCredential(username, password)
                        request.UseBinary = True
                        request.UsePassive = True

                        Dim buffer(1023) As Byte
                        Dim bytesIn As Long = 1
                        Dim totalBytesIn As Long = 0

                        Dim filepath As System.IO.FileInfo = New System.IO.FileInfo(file)
                        Dim ftpstream As System.IO.FileStream = filepath.OpenRead()
                        Dim flLength As Long = ftpstream.Length
                        Dim reqfile As System.IO.Stream = request.GetRequestStream()

                        Do Until bytesIn < 1
                            bytesIn = ftpstream.Read(buffer, 0, 1024)
                            If bytesIn > 0 Then
                                reqfile.Write(buffer, 0, bytesIn)
                                totalBytesIn += bytesIn
                            End If
                        Loop

                        reqfile.Close()
                        ftpstream.Close()