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

时间:2012-01-10 19:25:15

标签: .net vb.net ftp ftpwebrequest

我有这个link的工作代码,将文件上传到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目录中,文件将被覆盖吗?

6 个答案:

答案 0 :(得分:9)

查看MSDN文档,这将映射到FTP STOR命令。查看FTP STOR命令的定义,如果用户具有权限,它将覆盖现有文件。

所以在这种情况下,是的,文件将被覆盖。

答案 1 :(得分:3)

来自:Link

STOR(STORE)

STOR

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

答案 2 :(得分:3)

是的,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加密等),请使用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#示例:
How can we show progress bar for upload with FtpWebRequest

如果要上传文件夹中的所有文件,请参见
的C#示例 Upload directory of files using WebClient

答案 3 :(得分:-1)

重要的是要知道 文件只是对指向内存中字节数组的指针的引用。

当要求文件写入操作将文件写入指针时,它不会检查文件是否存在;简单地说,文件系统将允许操作继续,除非使用内存中的字节(虽然你可以强制覆盖)。

如果要在编写文件之前检查文件是否存在,请在此处使用我在VB.net中的GetDirectory方法:https://stackoverflow.com/a/28664731/2701974

答案 4 :(得分:-1)

使用此功能上传文件

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

如何使用:

&#39;使用FTP上传文件 UploadFile(&#34; c:\ UploadFile.doc&#34;,&#34; ftp://FTPHostName/UploadPath/UploadFile.doc&#34;,&#34; UserName&#34;,&#34;密码&#34;)

答案 5 :(得分:-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()