First we will make a method for searching files by mask. Works with .NET 4.0 and faster than Directory.GetFiles :
public static IEnumerable<string> nGetFiles(string path, string searchPatternExpression = "", SearchOption searchOption = SearchOption.AllDirectories) { Regex reSearchPattern = new Regex(searchPatternExpression); return Directory.EnumerateFiles(path, "*", searchOption).Where(file => reSearchPattern.IsMatch(Path.GetFileName(file))); }
Now so:
public static void SearchAllFiles() { //ΠΡΠΊΠΎΠΌΡΠ΅ ΡΠ°ΡΡΠΈΡΠ΅Π½ΠΈΡ: string LookForExt = "\.jpg|\.txt|\.asp"; //ΠΡΡΠΈ ΠΏΠ°ΠΏΠΎΠΊ ΠΈΡΡΠΎΡΠ½ΠΈΠΊΠ° ΠΈ ΠΏΡΠΈΡΠΌΠ½ΠΈΠΊΠ°: string SourcePath = @"D:\SourceDir\"; string TargetPath = @"D:\TargetPath\"; //ΠΠΎΠ»ΡΡΠ°Π΅ΠΌ ΡΠ°ΠΉΠ»Ρ ΠΈ ΠΊΠΎΠΏΠΈΡΡΠ΅ΠΌ ΠΈΡ
: IEnumerable<string> files = nGetFiles(SourcePath, LookForExt); foreach (f in files) //ΠΠΎΠΆΠ½ΠΎ Π±ΡΠ»ΠΎ ΠΈ ΡΠ°ΠΊ: foreach (f in nGetFiles(@"D:\SourceDir", LookForExt)) { try { File.Copy(f, TargetPath + Path.GetFileName(f), true); } catch (Exception e) { throw e; } } }
As a result, all files in the SourcePath folder and its subfolders will be scanned, the found files corresponding to the required extensions will be copied to the TargetPath without saving the subfolders structure. Moreover, if there is a file D:\SourceDir\test.asp and there is a file D:\SourceDir\111\test.asp , then in the resulting folder D:\TargetPath\ will be only one of these files that will be copied last ( and overwrite the existing one, and the first file copied to the target folder).
If you need to copy files from a folder while preserving the structure of subfolders and files, then here already gave the answer .