如何使用C#从FTP下载大量文件?

时间:2013-08-07 19:14:08

标签: c# ftpwebrequest

我需要按计划的时间间隔运行一个控制台应用程序,只需从FTP站点下载.pgp文件。必须下载FTP中的任何pgp文件。我找到了示例代码来获取FTP的目录列表,并在此处写了:

FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://ourftpserver");
        req.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        req.Credentials = new NetworkCredential("user", "pass");

        FtpWebResponse response = (FtpWebResponse)req.GetResponse();

        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        Console.WriteLine(reader.ReadToEnd());

        Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

        reader.Close();
        response.Close();

如何从目录列表中下载.pgp类型的所有文件并将其保存在我们服务器上的本地目录中?

4 个答案:

答案 0 :(得分:8)

FtpWebRequestFtpWebResponse对象确实设计为单个请求(即下载单个文件等)

您正在寻找FTP客户端。 .NET Framework中没有一个,但是有一个免费的,System.Net.FtpClient显然效果很好。

答案 1 :(得分:3)

有一个非常好的图书馆,您可以使用https://sshnet.codeplex.com/ 代码段: 您需要将要下载文件的文件夹路径作为localFilesPath和Ftp文件夹路径从您要下载的位置作为remoteFTPPath传递。

public static void DownloadFilesFromFTP(string localFilesPath, string remoteFTPPath)
        {
            using (var sftp = new SftpClient(Settings.Default.FTPHost, Settings.Default.FTPUsername, Settings.Default.FTPPassword))
            {
                sftp.Connect();
                sftp.ChangeDirectory(remoteFTPPath);
                var ftpFiles = sftp.ListDirectory(remoteFTPPath, null);
                StringBuilder filePath = new StringBuilder();
                foreach (var fileName in ftpFiles)
                {

                    filePath.Append(localFilesPath).Append(fileName.Name);
                    string e = Path.GetExtension(filePath.ToString());
                    if (e == ".csv")
                    {
                        using (var file = File.OpenWrite(filePath.ToString()))
                        {
                            sftp.DownloadFile(fileName.FullName, file, null);
                            sftp.Delete(fileName.FullName);
                        }
                    }
                    filePath.Clear();
                }
                sftp.Disconnect();
            }
        }

答案 2 :(得分:1)

ftp下载文件的代码。

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.0/my.txt");
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.Credentials = new NetworkCredential("userid", "pasword");
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();
        FileStream file = File.Create(@c:\temp\my.txt);
        byte[] buffer = new byte[32 * 1024];
        int read;
        //reader.Read(

        while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            file.Write(buffer, 0, read);
        }

        file.Close();
        responseStream.Close();
        response.Close();

答案 3 :(得分:1)

Ultimate FTP可以帮到你。 以下代码段演示了:

using ComponentPro.IO;
using ComponentPro.Net;

...

// Create a new instance.
Ftp client = new Ftp();

// Connect to the FTP server.
client.Connect("myserver");

// Authenticate.
client.Authenticate("userName", "password");

// ...

// Get all directories, subdirectories, and files from remote folder '/myfolder' to 'c:\myfolder'.
client.DownloadFiles("/myfolder", "c:\\myfolder");

// Get all directories, subdirectories, and files that match the specified search pattern from remote folder '/myfolder2' to 'c:\myfolder2'.
client.DownloadFiles("/myfolder2", "c:\\myfolder2", "*.pgp");

// or you can simply put wildcard masks in the source path, our component will automatically parse it.
// download all *.pgp files from remote folder '/myfolder2' to local folder 'c:\myfolder2'.
client.DownloadFiles("/myfolder2/*.pgp", "c:\\myfolder2");

// Download *.pgp files from remote folder '/myfolder2' to local folder 'c:\myfolder2'.
client.DownloadFiles("/myfolder2/*.pgp", "c:\\myfolder2");

// Get files in the folder '/myfolder2' only.
TransferOptions opt = new TransferOptions(true, RecursionMode.None, false, (SearchCondition)null, FileExistsResolveAction.Overwrite, SymlinksResolveAction.Skip);
client.DownloadFiles("/myfolder2", "c:\\myfolder2", opt);

// ...

// Disconnect.
client.Disconnect();

http://www.componentpro.com/doc/ftp有更多例子。