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

rev*_*kpi 5 .net c# ftp

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

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

Har*_*san 7

看看如何:使用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();  
Run Code Online (Sandbox Code Playgroud)

编辑 如果要在FTP服务器上重命名文件,请查看此Stackoverflow问题

  • 我会将您的读者放在使用区域中以便妥善处理.否则,最后添加reader.Dispose(). (2认同)

Mar*_*ryl 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");
Run Code Online (Sandbox Code Playgroud)

高级选项

如果您需要更大的控制权WebClient(例如TLS / SSL加密等),则无法使用,请使用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);
}
Run Code Online (Sandbox Code Playgroud)

进度监控

如果需要监视下载进度,则必须自己逐块复制内容:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关GUI进度(WinForms ProgressBar),请参见:
FtpWebRequest使用ProgressBar下载FTP


下载文件夹

如果要从远程文件夹
下载所有文件,请参见C#通过FTP下载所有文件和子目录