是的,FTP 协议会在上传时覆盖现有文件。
请注意,有更好的方法来实现上传。
使用 .NET 框架将二进制文件上传到 FTP 服务器最简单的方法是使用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")
如果您需要WebClient 不提供的更大控制(如TLS/SSL encryption、ascii/文本传输模式、活动模式、传输恢复等),请使用FtpWebRequest。简单的方法是使用Stream.CopyTo 将FileStream 复制到FTP 流:
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
如果你需要监控一个上传进度,你必须自己分块复制内容:
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
有关 GUI 进度 (WinForms ProgressBar),请参阅 C# 示例:
How can we show progress bar for upload with FtpWebRequest
如果您想上传文件夹中的所有文件,请参阅 C# 示例,地址为
Upload directory of files to FTP server using WebClient。