使用VB.NET上传文件到FTP站点

12

我从这个链接上找到了一个可行的代码,可以将文件上传到FTP站点:

' 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()

我想知道,如果FTP目录中已经存在该文件,那么该文件会被覆盖吗?

5个回答

10

查看MSDN文档,可以发现这对应于FTP STOR命令。根据FTP STOR命令的定义,如果用户有权限,则会覆盖现有文件。

因此,在这种情况下,是的,该文件将被覆盖。


9

是的,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.CopyToFileStream复制到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服务器


这个答案很完美,一个不错的补充是如何在你的FTP上创建目录:https://stackoverflow.com/questions/9031336/how-to-create-directory-on-ftp-server - MorenajeRD
1
使用WebClient.DownloadFile来从FTP站点下载文件,它与之类似,并且同样有效。已点赞,谢谢。 - Giorgio Barchiesi

3

来自:链接

STOR(存储)

STOR

此命令使FTP服务器接受通过数据连接传输的数据,并将数据存储为FTP服务器上的文件。如果在服务器站点上指定的路径名中存在文件,则其内容将被正在传输的数据替换。如果指定的路径名中的文件不存在,则在FTP服务器上创建一个新文件。


-1
使用此函数上传文件:
公共子 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

结束子程序

使用方法:

' 使用FTP上传文件 UploadFile("c:\UploadFile.doc", "ftp://FTPHostName/UploadPath/UploadFile.doc", "UserName", "Password")


-1

这是一个可用的代码,用于将文件上传到FTP服务器

               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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接