How to read folder and subfolder files?

Asked

Viewed 9,094 times

5

I have a function to read the files in the folder, and it’s not working. I need a functional function that reads files from folders and subfolders. Follows the code:

FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult result = fbd.ShowDialog();
            txtArquivo.Text = fbd.SelectedPath.ToString();

            //Marca o diretório a ser listado
            DirectoryInfo diretorio = new DirectoryInfo(txtArquivo.Text);
            //Executa função GetFile(Lista os arquivos desejados de acordo com o parametro)
            FileInfo[] Arquivos = diretorio.GetFiles("*.xml; *xlsx;");

            string[] files = System.IO.Directory.GetFiles(fbd.SelectedPath);
  • 1

    You used diretorio.GetFiles("*.xml; *xlsx;");. This way of using one more search pattern is not documented and in the tests I did, it was not possible to take the data of the two extensions, on the contrary, using the two separate patterns with ; brings back nothing.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

12

If you are using at least the . NET 4.0 basically you need it:

Directory.EnumerateFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories))

Documentation

Or you can use since version 2.0:

Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories))

Documentation

That is, what you needed to know is the overload with the parameter searchOptions.

If you want to get an extension, just change the search pattern of "*.*" for the extension you want. If you want to take more than one extension you will have to use the solution I have already indicated in my another answer.

There is a complete example from Microsoft using another approach.

Browser other questions tagged

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