是的,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加密、ascii/text传输模式、主动模式、传输恢复等),请使用
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#示例:
如何使用FtpWebRequest显示上传进度条
如果您想要上传一个文件夹中的所有文件,请参考以下C#示例:
使用WebClient上传文件夹中的文件到FTP服务器