我正在寻找一种方法来改进我的文件搜索。
目前我正在使用这种方法:
public IEnumerable<FileInfo> FindFilesInDirectory(string dirPath, string searchName)
{
return Directory.Exists(dirPath)
? Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories)
.ToList()
.ConvertAll(x => new FileInfo(x))
.Where(x => x.Name.ToLower().Contains(searchName.ToLower()))
: null;
}
有没有更快或更好的方法来做到这一点?
谢谢
最佳答案
不过,这几乎是微优化,您可以提高可读性并且可以添加异常处理。
您还应该使用 EnumerateFiles
(如果可能),它不需要在开始过滤之前将所有内容加载到内存中。此外,将 Equals
与 StringComparison.OrdinalIgnoreCase
一起使用,而不是 ToLower
,因为它更高效且更不容易出错 ( the Turkey test )。
public IEnumerable<FileInfo> FindFilesInDirectory(string dirPath, string searchName)
{
if (Directory.Exists(dirPath))
{
var dir = new DirectoryInfo(dirPath);
return dir.EnumerateFiles("*.*", SearchOption.AllDirectories)
.Where(fi => fi.Name.Equals(searchName, StringComparison.OrdinalIgnoreCase));
}
else
throw new ArgumentException("Directory doesn't exist.", dirPath);
}
关于c# - 查找目录中所有文件的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17422562/