Picking up a specific file in an FTP directory

Asked

Viewed 508 times

2

I have two methods, one sends a file by FTP and the other consumes a file by FTP.

The files have the dynamic name DateTime.Now each day a new file. example: collections-04-04-2017 16_00_19.xlsx

In the Send method I take the current date and give a getFile(); this always returns the file of the day, regardless of the time.

string DataAtual = DateTime.Now.ToString("yyyyMMdd");

//pathArquivoConsumido = local onde o arquivo esta que sera enviado;
DirectoryInfo objDiretorio = new DirectoryInfo(pathArquivoConsumido);
FileInfo[] arquivoData = objDiretorio.GetFiles("Coleta_" + DataAtual + "*.csv");

Now in the Archives consumption method, I would like to do the same thing as the line FileInfo[] arquivoData = objDiretorio.GetFiles("Coleta_" + DataAtual + "*.csv"); faz, só que no Diretório FTP

This is the line that I consume the file, but here I have to pass the full name,

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(pathFull);

so it is impossible to take only by date`

1 answer

3


It is necessary to make a request to FTP using the method ListDirectoryDetails, the return of this request will be the name of all files (and directories) separated by a line break.

After that just work with what was returned, for example, make a Split and create a array with the name of all the files and download the ones that are needed.

Follow an example.

var request = (FtpWebRequest)WebRequest.Create("ftp://www.seusite.com/pasta");  
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;  

request.Credentials = new NetworkCredential("usuario", "senha");    
var response = (FtpWebResponse)request.GetResponse();  

var responseStream = response.GetResponseStream();  
var reader = new StreamReader(responseStream);  
string arquivos = reader.ReadToEnd();

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

var arrayArquivos = names.Split(new string[] { "\r\n" }, 
                                    StringSplitOptions.RemoveEmptyEntries).ToList();

foreach(var arquivo in arrayArquivos.Where(a => a.StartsWith($"Coleta_{DataAtual}" 
                                             && a.EndsWith(".csv").ToList())
{
    Download(arquivo);
}

Browser other questions tagged

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