I have a task to clean up a large number of directories. I want to start at a directory and delete any sub-directories (no matter how deep) that contain no files (files will never be deleted, only directories). The starting directory will then be deleted if it contains no files or subdirectories. I was hoping someone could point me to some existing code for this rather than having to reinvent the wheel. I will be doing this using C#.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Using C# Code.
From here, Powershell script to remove empty directories:
Note: use at own risk!
Running the test on C:\Windows 1000 times on the 3 methods mentioned so far yielded this:
Running it on an empty folder yielded this (1000 times again):
So EnumerateFileSystemEntries is by far the best overall when you are checking for empty folders.
If you rely on
DirectoryInfo.Delete
only deleting empty directories, you can write a succinct extension methodUsage:
Here's a version that takes advantage of parallel execution to get it done faster in some cases:
Here's the same code in single threaded mode:
... and here's some sample code you could use to test results in your scenario:
... and here're some results from my machine for a directory that is on a file share across a wide area network. This share currently has only 16 subfolders and 2277 files.