最简单的方法
使用 .NET Framework 将文件上传到 FTP 服务器最简单的方式是使用 WebClient.UploadFile
方法:
WebClient client = new WebClient()
client.Credentials = new NetworkCredential("username", "password")
var url = "ftp://ftp.example.com/remote/path/file.zip"
client.UploadFile(url, @"C:\local\path\file.zip")
高级选项
如果你需要更多的控制权,而WebClient
没有提供(例如 TLS/SSL 加密,ascii/text 传输模式,主动模式,传输恢复,进度监测等),请使用FtpWebRequest
。最简单的方法是使用Stream.CopyTo
将FileStream
复制到FTP流中:
var url = "ftp://ftp.example.com/remote/path/file.zip"
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url)
request.Credentials = new NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.UploadFile
using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
fileStream.CopyTo(ftpStream)
}
进度监控
如果您需要监控上传的进度,您必须自己逐块复制内容:
var url = "ftp://ftp.example.com/remote/path/file.zip"
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url)
request.Credentials = new NetworkCredential("username", "password")
request.Method = WebRequestMethods.Ftp.UploadFile
using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
byte[] buffer = new byte[10240]
int read
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, read)
Console.WriteLine("Uploaded {0} bytes", fileStream.Position)
}
}
有关GUI进度(WinForms的ProgressBar
),请参阅C#示例:
如何在FtpWebRequest上传时显示进度条
上传文件夹
如果您想要上传文件夹中的所有文件,请参见
使用WebClient将文件夹中的文件上传到FTP服务器.
对于递归上传,请参见
C#中的递归上传到FTP服务器