Recursively delete files from a directory, but maintaining the integrity of the dir structure

To clean the test files, I try to do the following. But it does not clear files, nor does it generate an error.

Am I missing something obvious?

private void CleanUpTempDirFiles() { var fileGenerationDir = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "TestFilesDir")); fileGenerationDir.GetDirectories().ToList().ForEach(dir => dir.GetFiles().ToList().ForEach(file => file.Delete())); } 
+6
source share
5 answers

You can get all files in all subdirectories using SearchOption.AllDirectories

  fileGenerationDir.GetFiles("*", SearchOption.AllDirectories).ToList().ForEach(file=>file.Delete()); 
+9
source

This will be done:

  string[] filePaths = Directory.GetFiles( Path.Combine(Path.GetTempPath(), "TestFilesDir") , "*", SearchOption.AllDirectories); foreach (var filePath in filePaths) File.Delete(filePath); 
+1
source

First you use GetDirectories , which returns all subdirectories in your temp folder. Therefore, it does not return files in this directory. Therefore, you can do this instead:

 var tempDir = Path.Combine(Path.GetTempPath(), "TestFilesDir"); var allFilesToDelete = Directory.EnumerateFiles(tempDir, "*.*", SearchOption.AllDirectories); foreach (var file in allFilesToDelete) File.Delete(file); 

Removed by ToLists and used by SearchOption.AllDirectories , which searches recursively.

A practical guide. Iterating through a Directory Tree (C # Programming Guide)

+1
source

If the files are stored in the TestFilesDir folder, you do not need to get its subdirectories, just use:

 fileGenerationDir.GetFiles().ToList().ForEach(file => file.Delete()); 

otherwise you only delete subfolder files

0
source
 private void CleanUpTempDirFiles() { var fileGenerationDir = new DirectoryInfo( Path.Combine(Path.GetTempPath(), "TestFilesDir")); fileGenerationDir.GetFiles().ToList().ForEach(file => file.Delete()); } 
0
source

All Articles