3

Eu tenho uma FolderBrowserDialog e quando eu seleciono a pasta ele mostra a quantidade arquivos (todos, sem filtro). Como eu faço esse length somente com os arquivos de Excel (.xls, .xlsx).

Segue abaixo o código:

FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = Directory.GetFiles(fbd.SelectedPath);
System.Windows.Forms.MessageBox.Show("Arquivos na Pasta: " + files.Length.ToString(), "Alerta");
2
  • 1
    Congsegui parcialmente ! No array eu coloquei o seguinte comando. string[] files = System.IO.Directory.GetFiles(fbd.SelectedPath, "*.xlsx"); Ele ta verificando somente os arquivos xlsx, preciso que ele verifique também o xls. 29/08/2014 às 13:59
  • Dê uma olhada no tour. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
    – Maniero
    16/07/2015 às 0:47

2 Respostas 2

4

Pronto no .NET de forma mais simples, que pode ser feito para ambas extensões é isto:

FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = Directory.GetFiles(fbd.SelectedPath, "*.xls");
System.Windows.Forms.MessageBox.Show("Arquivos na Pasta: " + files.Length.ToString(), "Alerta");

O ideal seria especificar as duas extensões individualmente mas não há nada pronto no .NET. Do jeito que está qualquer coisa que comece com "xls" e tenha mais um caractere qualquer será considerado, então pode haver um efeito colateral indesejado, por exemplo pegar os arquivos "xlsh" que eventualmente você tenha, é improvável mas pode acontecer.

Uma opção melhor para .NET 4.5:

FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = Directory.EnumerateFiles(path)
                         .Where(file => file.ToLower().EndsWith("xls") ||
                                        file.ToLower().EndsWith("xlsx"))
System.Windows.Forms.MessageBox.Show("Arquivos na Pasta: " + files.Length.ToString(), "Alerta");

Retirado da resposta do jgauffin no SO.

Se não puder usar o .NET 4.5 basta trocar o método EnumerateFiles() por GetFiles(), a única desvantagem é a performance já que o segundo não usa lazy evaluation.

Ainda achei esta opção:

Multiple Filters On Directory.GetFiles Method

Simplificando o exemplo e adaptando para seu caso:

FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = Directory.GetFiles(fbd.SelectedPath, "*.xls");
files.AddRange(Directory.GetFiles(fbd.SelectedPath, "*.xlsx"));
System.Windows.Forms.MessageBox.Show("Arquivos na Pasta: " + files.Length.ToString(), "Alerta");

Ou simplificando e mantendo a generalidade:

public static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption) {
   return filters.Split('|').SelectMany(filter =>
          System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray();
}

Fonte: resposta do Albert no SO

Embora não sei se é necessário fazer isto. Veja a documentação indicando que o "xlsx" também é pego.

When you use the asterisk wildcard character in a searchPattern such as "*.txt", the number of characters in the specified extension affects the search as follows:

  • If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, "*.xls" returns both "book.xls" and "book.xlsx".

  • In all other cases, the method returns files that exactly match the specified extension. For example, ".ai" returns "file.ai" but not "file.aif". When you use the question mark wildcard character, this method returns only files that match the specified file extension. For example, given two files, "file1.txt" and "file1.txtother", in a directory, a search pattern of "file?.txt" returns just the first file, whereas a search pattern of "file.txt" returns both files.

Como há este comportamento não sei se qualquer solução é ideal a não ser fazer a loucura de criar um sistema próprio de captação dos arquivos e um filtro na com os próprios critérios. Dificilmente vale o esforço. Então acho que a segunda solução usando o LINQ acaba sendo a melhor.

Coloquei no GitHub para referência futura.

3

Utilizando Linq to Objects

1 - Forma

FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = System.IO.Directory.GetFiles(fbd.SelectedPath);
int length = files.Where(x => x.ToLower().EndsWith(".xls") || x.ToLower().EndsWith(".xlsx")).Count();
System.Windows.Forms.MessageBox.Show("Arquivos na Pasta: " + length.ToString(), "Alerta");

2 - Forma

FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = System.IO.Directory.GetFiles(fbd.SelectedPath);
int length = files
                .Where(x => x.ToLower().Substring(x.Length - 4).Equals(".xls") || x.ToLower().Substring(x.Length - 5).Equals(".xlsx"))
                .Count();
System.Windows.Forms.MessageBox.Show("Arquivos na Pasta: " + length.ToString(), "Alerta");
2
  • 1
    Exatamente o que eu precisava. Usei a forma 2 para resolver. 29/08/2014 às 18:11
  • @LeandroDíaz isso ai ... vlw
    – Maria
    29/08/2014 às 19:46

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .