Как да изтеглите множество файлове от FTP с помощта на C#?

Трябва да стартирам конзолно приложение на планирани интервали, което трябва да изтегля само .pgp файлове от FTP сайт. Всеки pgp файл във FTP трябва да бъде изтеглен. Намерих примерния код за получаване на списък с директории на 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 от списъка с директории и да ги запазя в локална директория на нашия сървър?


person SidC    schedule 07.08.2013    source източник
comment
Анализирайте отговора и използвайте цикъл.   -  person SLaks    schedule 07.08.2013
comment
SLaks Бихте ли разяснили с примерен код?   -  person SidC    schedule 07.08.2013


Отговори (4)


Обектите FtpWebRequest и FtpWebResponse наистина са проектирани да правят единични заявки (т.е. изтегляне на единични файлове и т.н.)

Търсите FTP клиент. В .NET Framework няма такъв, но има безплатен, System.Net.FtpClient, който очевидно работи доста добре.

person Jim Mischel    schedule 07.08.2013
comment
Благодаря ти много! Прочетох толкова много публикации на този сайт, MSDN и други, но вашата информация е директна и точна. Оценявам го. Ще изтегля това сега :) - person SidC; 08.08.2013

Има много добра библиотека, която можете да използвате 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();
            }
        }
person Thakur Rock    schedule 30.12.2014
comment
Започнах да използвам това въз основа на този отговор, много хубаво! - person Michael A; 20.07.2015

код за изтегляне на файл от 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();
person Chandresh Singh Rathore    schedule 01.10.2013

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 има още примери.

person Alexey Semenyuk    schedule 13.01.2015
comment
Имайте предвид, че това е платена библиотека и не е страхотна. Бих избегнал. Има много добри безплатни решения! - person Michael A; 20.07.2015