[英]Searching a lot of text files for a specific text written in textbox and display them
I am trying to search many text files from a particular directory and then textchanged event to find text in all files and display on screen only lines which contain that text. 我试图从特定目录中搜索许多文本文件,然后使用textchanged事件在所有文件中查找文本,并在屏幕上仅显示包含该文本的行。
Currently it is working but it is too slow. 目前它正在运作但速度太慢。 I am posting a function which searches text and display in listbox.
我发布了一个搜索文本并在列表框中显示的功能。 what could be most efficient way to make it work little speedy.
什么是使它快速工作的最有效方法。
listBox2.Items.Clear();
ArrayList lines = new ArrayList();
if (txtfile.Count > 0)
{
for (int i = 0; i < txtfile.Count; i++)
{
lines.AddRange((File.ReadAllLines(Path.Combine(path, txtfile[i].ToString()))));
}
for (int i = 0; i < lines.Count; i++)
{
if(lines[i].ToString().IndexOf(txt,StringComparison.InvariantCultureIgnoreCase)>=0)
{
listBox2.Items.Add(lines[i].ToString());
}
}
}
How many files are you searching? 你在搜索多少个文件? You could always index them , store the contents in a SQL database, and of course use Parallel.For
您始终可以索引它们,将内容存储在SQL数据库中,当然也可以使用Parallel.For
Parallel.For(1, 1000, i =>
{
//do something here.
}
);
I would use Directory.EnumerateFiles
and File.ReadLines
since they are less memory hungry: 我会使用
Directory.EnumerateFiles
和File.ReadLines
因为它们的内存不足:
var matchingLines = Directory.EnumerateFiles(path, ".txt", SearchOption.TopDirectoryOnly)
.SelectMany(fn => File.ReadLines(fn))
.Where(l => l.IndexOf(txt, StringComparison.InvariantCultureIgnoreCase) >= 0);
foreach (var line in matchingLines)
listBox2.Items.Add(line);
I would also search only when the user triggers it explicitely, so on button-click and not on text-changed. 我也会在用户明确触发它时进行搜索,所以按下按钮而不是文本更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.