Download all files from a folder on FTP?

Asked

Viewed 2,237 times

1

Good morning,

I am developing a system that does file exchange . txt via FTP. I need to download all the files that are in a certain folder.

Today I can download one file at a time, in case I pass the connection credentials, folder name and file name, but this way is not meeting my need.

The code below is working for a single download.

Can anyone tell me what I need to adjust in this code below ? If this is possible to meet my need.

Thank you

    public static void StartDownloads(out string pstrMsg, out bool pbooRetorno, string pstrUrl, string pstrLocal, string pstrUsuario, string pstrSenha)
    {
        pstrMsg = string.Empty;
        pbooRetorno = false;

        try
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(pstrUrl);
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            // Credenciais utilizadas para conectar no servidor FTP
            request.Credentials = new NetworkCredential(pstrUsuario, pstrSenha);

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                Stream responseStream = response.GetResponseStream();

                using (StreamReader reader = new StreamReader(responseStream))
                {
                    // Cria o arquivo no local especificado
                    using (StreamWriter writer = new StreamWriter(pstrLocal))
                    {
                        string strLinhaArquivo = reader.ReadLine();

                        while (!String.IsNullOrEmpty(strLinhaArquivo))
                        {
                            // Gravar as informações no arquivo
                            writer.Write(strLinhaArquivo);

                            // Verifica se o arquivo extraido contém linha
                            if (!String.IsNullOrEmpty((strLinhaArquivo = reader.ReadLine())))
                            {
                                // Inseri uma nova linha no arquivo
                                writer.WriteLine();
                            }
                        }
                    }
                }
            }

            Uri uri = new Uri(pstrUrl);

            // Método deleta o arquivo assim que o download acaba
            DeleteFileOnServer(uri, pstrUsuario, pstrSenha); // request);

            pbooRetorno = true;
        }
        catch (Exception ex)
        {
            pstrMsg = string.Format("Erro:\nMétodo 'StartDownloads'\nDetalhes: {0}", ex.Message);

            pbooRetorno = false;
        }
    }

2 answers

4


Well, I’ve used the code below:

public void BaixarTodosArquivosDirFTP(string urlFTP, string usuario, string senha, string dirLocal)
{
    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(urlFTP);
    ftpRequest.Credentials = new NetworkCredential(usuario, senha);
    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
    FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
    StreamReader streamReader = new StreamReader(response.GetResponseStream());           
    List<string> diretorios = new List<string>();            

    string line = streamReader.ReadLine();
    while (!string.IsNullOrEmpty(line))
    {
        diretorios.Add(line);
        line = streamReader.ReadLine();
    }
    streamReader.Close();


    using (WebClient ftpClient = new WebClient())
    {
        ftpClient.Credentials = new System.Net.NetworkCredential(usuario, senha);

        for (int i = 0; i <= diretorios.Count-1; i++)
        {
            if (diretorios[i].Contains("."))
            {

                string pathRemota = urlFTP + diretorios[i].ToString();
                string pathLocal = Path.Combine(urlFTP, diretorios[i].ToString());
                ftpClient.DownloadFile(pathRemota, pathLocal);
            }
        }
    }
}

I took a question from Stackoverflow in English:

https://stackoverflow.com/questions/20526536/how-to-transfer-multiple-files-from-ftp-server-to-local-directory-using-c

  • good morning @Julio Borges, I will see if this solution meets my need. Thank you

  • @Diegofarias, Ok, I forgot to comment on the code that it uses the code if (diretorios[i].Contains(".")) to identify if what was listed is a file or if it is a directory, whereas the listed files have extension.

  • @Diegofarias, If the answer answered you, accept the same.

-2

ftpClient.DownloadFile(pathRemota, pathLocal);

I went to download several test files but gave error in this line saying "There is no support for the given path format."

Could you help me?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.