如何从FTP获取文件(使用C#)?

时间:2011-12-26 15:13:23

标签: c# .net ftp

现在我知道如何将文件从一个目录复制到另一个目录,这非常简单。

但是现在我需要对来自FTP服务器的文件做同样的事情。你能给我一些例子,说明如何在更改名称的同时从FTP获取文件吗?

2 个答案:

答案 0 :(得分:7)

查看How to: Download Files with FTPdownloading 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

将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 FTP download with ProgressBar

正在下载文件夹

如果要从远程文件夹下载所有文件,请参阅
C# Download all files and subdirectories through FTP