[英]Fastest way to search for contents of files
I'm doing a search for specific text in web files. 我正在搜索Web文件中的特定文本。 The user enters the text.
用户输入文本。 There are about 850 files I have to search.
我必须搜索大约850个文件。 The code below accomplishes what I want but it takes about 11-13 seconds.
下面的代码完成了我想要的,但是大约需要11-13秒。 This code is in a web service I call from a web page using $.ajax GET.
这段代码在我使用$ .ajax GET从网页调用的Web服务中。 Is there a way I can improve the code so the search goes faster?
有什么方法可以改善代码,以便搜索更快? Or should I be looking at other areas instead of my code?
还是应该查看其他区域而不是代码?
I do the replaces in the document because of how the files are created (they create web files using MS Word...another battle) and it improves my search results. 由于文件的创建方式,我在文档中进行替换(它们使用MS Word创建网络文件...另一场战斗),并且它改善了我的搜索结果。
var searchResults = new StringBuilder();
var parameters = searchParameters.Split('|');
var searchOnCompletePhrase = bool.Parse(parameters[1]);
var completePhrasePattern = @"\b(?:" + Regex.Escape(parameters[0].ToString()) + @")\b";
var files = Directory.GetFiles(path, "*.htm");
if (searchOnCompletePhrase && searchPhrase.Length > 1)
{
foreach (var currentFile in files)
{
document.Load(currentFile);
contents = document.DocumentNode.InnerText.Replace("\r", string.Empty)
.Replace("\n", string.Empty)
.Replace(" ", string.Empty)
.Replace(" ", " ");
if (contents.ToLower().IndexOf(searchPhrase.ToLower()) > -1)
{
searchResults.AppendLine(currentFile);
searchResults.Append("|");
}
}
}
else
{
var keywords = parameters[0].Split(' ');
foreach (var currentFile in files)
{
document.Load(currentFile);
contents = document.DocumentNode.InnerText.Replace("\r", string.Empty)
.Replace("\n", string.Empty)
.Replace(" ", string.Empty)
.Replace(" ", " ");
var found = true;
foreach (var word in keywords)
{
if (!SearchCurrentWord(word.ToString()))
{
found = false;
break;
}
}
if (found)
{
searchResults.AppendLine(currentFile);
searchResults.Append("|");
}
}
}
也许您应该尝试使用Parallel.Foreach而不是foreach循环,以避免顺序等待磁盘中的每个文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.