Ednilton, Directory.GetFiles
returns the names of files (including paths) in the specified directory. For you to list all files, including those for subdirectories, you need to pass more than SearchOption
.
Just by simply changing your foreach
foreach (string arquivo in Directory.GetFiles(origem, filtro, SearchOption.AllDirectories))
Eventually Directory.GetFiles
may not be allowed to access a particular directory, thus launching a UnauthorizedAccessException
.
One solution would be to first get all directories using GetDirectories
and then go through all the directories by searching for the files using GetFiles
:
public static List<string> GetFiles(string path, string searchPattern, SearchOption searchOption)
{
var diretorios = Directory.GetDirectories(path);
List<string> arquivos = new List<string>();
try
{
foreach (var diretorio in diretorios)
{
arquivos.AddRange(Directory.GetFiles(diretorio, searchPattern, searchOption).ToList());
}
}
catch (UnauthorizedAccessException)
{
}
return arquivos;
}
The Main
method would look like this:
public static void Main()
{
string filtro = "*.xlsx";
string diretorioDestino = @"D:\temp";
List<string> origens = new List<string>();
origens.Add(@"C:\Users\pablotondolo\Documents");
//
foreach (var origem in origens)
{
foreach (string arquivo in GetFiles(origem, filtro, SearchOption.AllDirectories))
{
File.Copy(arquivo, Path.Combine(diretorioDestino, Path.GetFileName(arquivo)));
}
}
}
NOTE: The excel extension is xlsx
and not xslx
.