Get all sub directories that only contain files
I have a path and I want to list the subdirectories under it, where each subdirectory doesn't contain any other directory. (Only those subdirectories which don't contain folders, but only files.)
开发者_如何学PythonAny smart way to do so?
It is my understanding that you want to list the subdirectories below a given path that contain only files.
static IEnumerable<string> GetSubdirectoriesContainingOnlyFiles(string path)
{
return from subdirectory in Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
where Directory.GetDirectories(subdirectory).Length == 0
select subdirectory;
}
DirectoryInfo
DirectoryInfo dInfo = new DirectoryInfo(<path to dir>);
DirectoryInfo[] subdirs = dInfo.GetDirectories();
You can use the Directory.GetDirectories
method.
However I'm not sure I understood your question correctly... could you clarify ?
Based on Havard's answer, but a little shorter (and maybe slightly easier to read because it uses !Subdirs.Any()
instead of Subdirs.Length == 0
):
static IEnumerable<string> GetSubdirectoriesContainingOnlyFiles(string path)
{
return Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
.Where( subdir => !Directory.GetDirectories(subdir).Any() );
}
Also note, that this requires using System.Linq;
to work, since it uses the LINQ query language. (And of course using System.IO;
for the Directory
class :))
精彩评论