两者都适用于 FTPWebClient.UploadFile
和WebClient.DownloadFile
二进制文件。
上传
WebClient client = 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 加密、ascii/文本传输模式、传输恢复等),请使用FtpWebRequest
. 简单的方法是FileStream
使用以下命令复制到 FTP 流Stream.CopyTo
:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
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);
}
如果您需要监控上传进度,您必须自己按块复制内容:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
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
),请参阅:
我们如何使用 FtpWebRequest 显示上传进度条
如果要上传文件夹中的所有文件,请参阅
C# 中的递归上传到 FTP 服务器。
下载
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
"ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
如果您需要更大的控制,WebClient
但不提供(如TLS/SSL 加密、ascii/文本传输模式、恢复传输等),请使用FtpWebRequest
. 简单的方法是将 FTP 响应流复制到FileStream
使用Stream.CopyTo
:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
ftpStream.CopyTo(fileStream);
}
如果您需要监控下载进度,您必须自己按块复制内容:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;
using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
byte[] buffer = new byte[10240];
int read;
while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, read);
Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
}
}
有关 GUI 进度 (WinForms ProgressBar
),请参阅:
FtpWebRequest FTP 下载与 ProgressBar
如果要从远程文件夹下载所有文件,请参阅
C# 通过 FTP 下载所有文件和子目录。