简体   繁体   English

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

[英]Upload file to FTP site using VB.NET

I have this working code from this link , to upload a file to an ftp site:我从这个链接有这个工作代码,将文件上传到 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()

I wonder, if the file already exists in the ftp directory, the file will be overwritten?请问,如果文件已经存在于ftp目录下,文件会被覆盖吗?

Looking at the MSDN documentation this maps to the FTP STOR command.查看MSDN文档,这映射到 FTP STOR 命令。 Looking at the definition for the FTP STOR command it will overwrite existing files, if the user has permissions.查看 FTP STOR 命令的定义,如果用户有权限,它将覆盖现有文件。

So in this case, yes the file would be overwritten.所以在这种情况下,是的,文件将被覆盖。

Yes, FTP protocol overwrites existing files on upload.是的,FTP 协议会在上传时覆盖现有文件。


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 :使用 .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")

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 .如果您需要更好的控制,而WebClient不提供(如TLS/SSL 加密、ascii/文本传输模式、主动模式、传输恢复等),请使用FtpWebRequest Easy way is to just copy a FileStream to FTP stream using Stream.CopyTo :简单的方法是使用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

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:有关 GUI 进度 (WinForms ProgressBar ),请参阅 C# 示例,网址为:
How can we show progress bar for upload with FtpWebRequest我们如何使用 FtpWebRequest 显示上传进度条

If you want to upload all files from a folder, see C# example at如果要上传文件夹中的所有文件,请参阅 C# 示例
Upload directory of files to FTP server using WebClient .使用 WebClient 将文件目录上传到 FTP 服务器

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.此命令使 FTP 服务器接受通过数据连接传输的数据并将数据作为文件存储在 FTP 服务器上。 If the file specified in pathname exists at the server site, then its contents shall be replaced by the data being transferred.如果 pathname 中指定的文件存在于服务器站点,则其内容将被正在传输的数据替换。 A new file is created at the FTP server if the file specified in pathname does not already exist.如果路径名中指定的文件不存在,则会在 FTP 服务器上创建一个新文件。

It is important to know that, Files are just references to pointers that point to an array of bytes in memory.重要的是要知道,文件只是对指向内存中字节数组的指针的引用。

When a file writing operation is asked to write a file to a pointer, it will not check if the file exist;当一个文件写入操作被要求将一个文件写入一个指针时,它不会检查该文件是否存在; Simply, the file system will allow the operation to continue unless the bytes in memory are being used ( although you can force overwrite ).简单地说,文件系统将允许操作继续,除非正在使用内存中的字节(尽管您可以强制覆盖)。

If you want to check if a file exist before writing the file use my GetDirectory method in VB.net here: https://stackoverflow.com/a/28664731/2701974如果您想在写入文件之前检查文件是否存在,请在此处使用我在 VB.net 中的 GetDirectory 方法: https : //stackoverflow.com/a/28664731/2701974

Use This Function to Upload file使用此功能上传文件

Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String) 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) 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结束子

HOW TO USE:如何使用:

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

this is working code to upload files to a FTP server这是将文件上传到 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM