如何过滤多个扩展?
我试过了:
FileInfo[] Files = dinfo.GetFiles("*.jpg;*.tiff;*.bmp"); FileInfo[] Files = dinfo.GetFiles("*.jpg,*.tiff,*.bmp");
为什么不创建扩展方法?更具可读性。
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) { if (extensions == null) throw new ArgumentNullException("extensions"); IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>(); foreach(string ext in extensions) { files = files.Concat(dir.GetFiles(ext)); } return files; }
编辑:一个更有效的版本:
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) { if (extensions == null) throw new ArgumentNullException("extensions"); IEnumerable<FileInfo> files = dir.EnumerateFiles(); return files.Where(f => extensions.Contains(f.Extension)); }
用法:
DirectoryInfo dInfo = new DirectoryInfo(@"c:\MyDir"); dInfo.GetFilesByExtensions(".jpg",".exe",".gif");