出于文件和目录搜索的目的,我想提供具有广泛搜索机会的多线程 .NET 库。
您可以在 GitHub 上找到有关库的所有信息:https://github.com/VladPVS/FastSearchLibrary
如果你想下载它,你可以在这里下载:https://github.com/VladPVS/FastSearchLibrary/releases
如果您有任何问题,请向他们提问。
运行速度非常快。自己检查吧!
这是如何使用它的一个示范性示例:
class Searcher
{
private static object locker = new object();
private FileSearcher searcher;
List<FileInfo> files;
public Searcher()
{
files = new List<FileInfo>();
}
public void Startsearch()
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
searcher = new FileSearcher(@"C:\", (f) =>
{
return Regex.IsMatch(f.Name, @".*[Dd]ragon.*.jpg$");
}, tokenSource);
searcher.FilesFound += (sender, arg) =>
{
lock (locker) // using a lock is obligatorily
{
arg.Files.ForEach((f) =>
{
files.Add(f);
Console.WriteLine($"File location: {f.FullName}, \nCreation.Time: {f.CreationTime}");
});
if (files.Count >= 10)
searcher.StopSearch();
}
};
searcher.SearchCompleted += (sender, arg) =>
{
if (arg.IsCanceled)
Console.WriteLine("Search stopped.");
else
Console.WriteLine("Search completed.");
Console.WriteLine($"Quantity of files: {files.Count}");
};
searcher.StartSearchAsync();
}
}
这是其他示例的一部分:
***
List<string> folders = new List<string>
{
@"C:\Users\Public",
@"C:\Windows\System32",
@"D:\Program Files",
@"D:\Program Files (x86)"
}; // list of search directories
List<string> keywords = new List<string> { "word1", "word2", "word3" }; // list of search keywords
FileSearcherMultiple multipleSearcher = new FileSearcherMultiple(folders, (f) =>
{
if (f.CreationTime >= new DateTime(2015, 3, 15) &&
(f.Extension == ".cs" || f.Extension == ".sln"))
foreach (var keyword in keywords)
if (f.Name.Contains(keyword))
return true;
return false;
}, tokenSource, ExecuteHandlers.InCurrentTask, true);
***
而且可以使用简单的静态方法:
List<FileInfo> files = FileSearcher.GetFilesFast(@"C:\Users", "*.xml");
请注意,此库的所有方法都不会抛出 UnauthorizedAccessException 而不是标准的 .NET 搜索方法。
如果您使用多核处理器,此库的其他快速方法的执行速度至少比简单的单线程递归算法快 2 倍。