Ednilton, the Directory.GetFiles returns the filenames (including paths) in the specified directory. To list all the files, including those of subdirectories, you need to pass more the SearchOption.
Simply change your own foreach
foreach (string arquivo in Directory.GetFiles(origem, filtro, SearchOption.AllDirectories))
Eventually the Directory.GetFiles may not be allowed to access a particular directory, thus launching a UnauthorizedAccessException.
A solution would be first you get all the directories using the GetDirectories and then go through all the directories searching for the files using the 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 method Main 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 extension of excel is xlsx and not xslx.
And what’s the problem you’re having?
– Jéf Bueno
See if it helps you in any way: http://answall.com/q/30797/101 and http://answall.com/a/75171/101
– Maniero
The
Directory.GetFileshas a third parameter which isSearchOption, passes the value ofSearchOption.AllDirectories. By default it will return only the files from the specified directory.– Pablo Tondolo de Vargas