Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively delete files from a Directory but keeping the dir structure intact

For cleaning up the test files, am trying to do the below. But its not clearing the files as well as not generating 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()));
    }
like image 542
Codex Avatar asked Nov 28 '12 11:11

Codex


2 Answers

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

 fileGenerationDir.GetFiles("*", SearchOption.AllDirectories).ToList().ForEach(file=>file.Delete());
like image 65
Tilak Avatar answered Nov 09 '22 20:11

Tilak


You are using GetDirectories first which returns all sub-directories in your temp folder. Hence it does not return the files in this directory. So you might want to 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 the ToLists and used SearchOption.AllDirectories which searches recursively.

How to: Iterate Through a Directory Tree (C# Programming Guide)

like image 26
Tim Schmelter Avatar answered Nov 09 '22 21:11

Tim Schmelter