Upload file to FTP site using VB.NET
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, ascii/text transfer mode, active mode, transfer resuming, 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 to FTP server using WebClient.
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.
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.