最简单的方法
使用.NET框架将文件上传到FTP服务器的最简单的方法是使用WebClient.UploadFile
method:
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
使用Stream.CopyTo
以下命令将a复制到FTP流:
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
),请参见以下C#示例:
如何显示使用FtpWebRequest上传的进度栏
上载资料夹
如果要从文件夹上载所有文件,请参阅
使用WebClient将文件目录上载到FTP服务器。
有关递归上传,请参见
C#中的递归上传到FTP服务器