现在我知道如何将文件从一个目录复制到另一个目录,这非常简单。
但是现在我需要对来自FTP服务器的文件做同样的事情。你能给我一些例子,说明如何在更改名称的同时从FTP获取文件吗?
答案 0 :(得分:7)
查看How to: Download Files with FTP或downloading all files in directory ftp and 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 question
答案 1 :(得分:5)
使用.NET框架从FTP服务器下载二进制文件的最简单方法是使用WebClient.DownloadFile
。
它采用源远程文件和目标本地文件的路径。因此,如果需要,可以为本地文件使用不同的名称。
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加密等),请使用FtpWebRequest
。简单的方法是使用Stream.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"))
{
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 download with ProgressBar
如果要从远程文件夹下载所有文件,请参阅
C# Download all files and subdirectories through FTP