Som*_*ody 9 .net vb.net ftp ftpwebrequest
我从这个链接有这个工作代码,将文件上传到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()
Run Code Online (Sandbox Code Playgroud)
我想知道,如果文件已存在于ftp目录中,该文件是否会被覆盖?
是的,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")
Run Code Online (Sandbox Code Playgroud)
如果您需要更好的控制WebClient
(如TLS/SSL 加密、ascii/文本传输模式、主动模式、传输恢复等),请使用FtpWebRequest
. 简单的方法是FileStream
使用Stream.CopyTo
以下命令将 a 复制到 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
Run Code Online (Sandbox Code Playgroud)
如果您需要监控上传进度,您必须自己分块复制内容:
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
Run Code Online (Sandbox Code Playgroud)
对于 GUI 进度 (WinForms ProgressBar
),请参阅 C# 示例:
How can we show progress bar for upload with FtpWebRequest
如果要上传文件夹中的所有文件,请参阅
使用 WebClient 将文件目录上传到 FTP 服务器中的C# 示例。
归档时间: |
|
查看次数: |
53224 次 |
最近记录: |