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()));
}
You can get all the files in all the the subdirectories using SearchOption.AllDirectories
fileGenerationDir.GetFiles("*", SearchOption.AllDirectories).ToList().ForEach(file=>file.Delete());
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With