排除子目录在目录循环 [英] Exclude subdirectories in a directory loop
问题描述
在一个.NET code,我有一个循环,需要从D-所有.wav文件:\ Temp和其子目录:
的String [] fileHolder = Directory.GetFiles(D:\\ temp的,*。WAV,SearchOption.AllDirectories);
我要排除具有blablabla在他们的文件夹名称中的所有.wav文件从文件夹中来了。
就如何做到这一点?
P.S。这类似于<一href="http://stackoverflow.com/questions/12646507/exclude-directories-that-contain-sub-directories/12984087#12984087">Exclude目录中包含子目录?,但我一直没能成功使用这一课题的答案。
的IEnumerable&LT;字符串&GT;文件=
从f由于Directory.GetFiles(D:\\ temp的,* .WAV,SearchOption.AllDirectories)
在那里!Path.GetDirectoryName(F)。载(blablabla)
选择F;
添加几个条件:
var中的文件,从F =在Directory.GetFiles(D:\\ temp的,* .WAV,SearchOption.AllDirectories)
让目录名= Path.GetDirectoryName(F)
其中,directoryName.Contains(blablabla)及!&安培;
!direcotyName.Contains(富)
选择F;
另一种解决方案:(我认为这Path.GetDirectoryName不是最快的操作)
公共静态的IEnumerable&LT;字符串&GT;的GetFiles(路径字符串,字符串是searchPattern,
FUNC&LT;字符串,布尔&GT; dirSelector)
{
如果(!dirSelector(路径))
产生中断;
的foreach(在Directory.GetFiles var文件(路径,是searchPattern))
得到回报的文件;
的foreach(在Directory.GetDirectories VAR目录(路径))
的foreach(在的GetFiles var文件(目录,是searchPattern,dirSelector))
得到回报的文件;
}
用法:
Func键&LT;字符串,布尔&GT; dirSelector =(D)=&GT; !d.Contains(blablabla);
字符串[]文件=的GetFiles(D:\\ temp的,* .WAV,dirSelector).ToArray();
In a .NET code, I have a loop that takes all .wav files from D:\Temp and its subdirectories :
string[] fileHolder = Directory.GetFiles("D:\\Temp","*.wav", SearchOption.AllDirectories);
I want to exclude all .wav files coming from folders that have "blablabla" in their folder name.
How do do this ?
P.S. This is similar to Exclude directories that contain sub directories?, but I haven't been able to use successfully the answers of this topic.
IEnumerable<string> files =
from f in Directory.GetFiles("D:\\Temp", "*.wav", SearchOption.AllDirectories)
where !Path.GetDirectoryName(f).Contains("blablabla")
select f;
Adding several conditions:
var files = from f in Directory.GetFiles("D:\\Temp", "*.wav", SearchOption.AllDirectories)
let directoryName = Path.GetDirectoryName(f)
where !directoryName.Contains("blablabla") &&
!direcotyName.Contains("foo")
select f;
Another solution: (I think that Path.GetDirectoryName is not fastest possible operation)
public static IEnumerable<string> GetFiles(string path, string searchPattern,
Func<string, bool> dirSelector)
{
if (!dirSelector(path))
yield break;
foreach (var file in Directory.GetFiles(path, searchPattern))
yield return file;
foreach (var dir in Directory.GetDirectories(path))
foreach (var file in GetFiles(dir, searchPattern, dirSelector))
yield return file;
}
Usage:
Func<string, bool> dirSelector = (d) => !d.Contains("blablabla");
string[] files = GetFiles("D:\\Temp", "*.wav", dirSelector).ToArray();
这篇关于排除子目录在目录循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!