【问题标题】:Searching a lot of text files for a specific text written in textbox and display them在大量文本文件中搜索文本框中写入的特定文本并显示它们
【发布时间】:2013-04-03 09:04:44
【问题描述】:

我正在尝试从特定目录中搜​​索许多文本文件,然后使用 textchanged 事件在所有文件中查找文本,并仅在屏幕上显示包含该文本的行。

目前它正在运行,但速度太慢。我正在发布一个搜索文本并在列表框中显示的功能。什么可能是最有效的方法来让它工作得有点快。

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());
        }       
    }

}

【问题讨论】:

  • 什么是txt,什么是txtfile
  • 对于TextChanged 事件,Textbox 中文本的每次更改都会重新触发搜索,这将导致性能下降。可能会根据Button_Click 而不是TextChanged 事件触发搜索,该事件将针对添加或删除的每个字符触发。
  • @TimSchmelter txt 是要搜索的文本,txtfile 是包含所有要搜索的文件的数组

标签: c# .net performance search


【解决方案1】:

您要搜索多少个文件?您可以随时索引它们,将内容存储在 SQL 数据库中,当然还可以使用 Parallel.For

Parallel.For(1, 1000, i =>
    {
        //do something here.
    }
);

【讨论】:

【解决方案2】:

我会使用Directory.EnumerateFilesFile.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);

我也只会在用户明确触发它时搜索,所以在按钮单击而不是在文本更改时搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多