【问题标题】:Upload file to FTP site using VB.NET使用 VB.NET 将文件上传到 FTP 站点
【发布时间】:2012-02-07 05:15:31
【问题描述】:

我有这个来自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目录下已经存在该文件,会不会覆盖该文件?

【问题讨论】:

    标签: .net vb.net ftp ftpwebrequest


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      是的,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.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 to FTP server using WebClient

      【讨论】:

      • 这个答案很完美,一个很好的补充是如何在你的 ftp 上创建目录:stackoverflow.com/questions/9031336/…
      • 使用了类似的 WebClient.DownloadFile 从 FTP 站点下载文件,效果也很好。点赞,谢谢。
      【解决方案3】:

      发件人:Link

      存储(存储)

      存储

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

      【讨论】:

        【解决方案4】:

        使用此功能上传文件

        Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String, ByVal _FTPUser As String, ByVal _FTPPass As String)

        将 _FileInfo 调暗为新 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", "用户名", "密码")

        【讨论】:

          【解决方案5】:

          这是将文件上传到 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()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-04-10
            • 1970-01-01
            • 2011-10-06
            • 1970-01-01
            • 2012-06-09
            • 1970-01-01
            • 1970-01-01
            • 2013-02-22
            相关资源
            最近更新 更多