[英]How can I get file from FTP (using C#)?
现在我知道如何将文件从一个目录复制到另一个目录,这真的很简单。
但现在我需要对来自 FTP 服务器的文件做同样的事情。 你能给我一些例子,如何在改变文件名的同时从 FTP 获取文件?
看看如何:使用 FTP 下载文件或下载目录 ftp 和 c# 中的所有文件
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
reader.Dispose();
response.Close();
编辑如果要重命名 FTP 服务器上的文件,请查看此Stackoverflow 问题
使用 .NET 框架从 FTP 服务器下载二进制文件的最简单方法是使用WebClient.DownloadFile
。
它需要一个指向源远程文件的 URL 和一个指向目标本地文件的路径。 因此,如果需要,您可以为本地文件使用不同的名称。
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
。 简单的方法是使用Stream.CopyTo
将 FTP 响应流复制到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"))
{
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 使用 ProgressBar 进行 FTP 下载
如果要从远程文件夹下载所有文件,请参阅
C# 通过 FTP 下载所有文件和子目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.