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.
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
Parallel.For(1, 1000, i =>
{
//do something here.
}
);
I would use Directory.EnumerateFiles
and File.ReadLines
since they are less memory hungry:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.