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

问题描述 投票:5回答:2

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

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

c# .net ftp
2个回答
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","[email protected]");

            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


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 encryption等),使用FtpWebRequest。简单的方法是使用FileStream将FTP响应流复制到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);
}

进度监测

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

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

© www.soinside.com 2019 - 2024. All rights reserved.