I'm using Directory.GetFiles()
to search files in a multi-folder directory and some of these folders are too big so the search could take up to 60 seconds. In the code below a search starts a second after the user stops typing, this works great when the user types the file name and does not pauses while typing it but if he/she pauses in the middle of the word the search will start and will not stop until it finishes even if he/she starts typing again.
What I would like to do is stop searches while the user is typing, possibly in the inputFileName_TextChanged method.
Is there a way to stop a search that has been already started when using Directory.GetFiles
?
using System.Timers;
using System.IO;
namespace findFileTest
{
public partial class MainWindow : Window
{
Timer timer = new Timer();
public MainWindow()
{
InitializeComponent();
timer.Elapsed += new ElapsedEventHandler(TimerEvent);
timer.Interval = 1000;
timer.Enabled = true;
timer.Stop();
}
private void inputFileName_TextChanged(object sender, TextChangedEventArgs e)
{
// How to stop the search currently in process here
timer.Stop();
timer.Start();
}
public void TimerEvent(object source, ElapsedEventArgs e)
{
timer.Stop();
findFile();
}
private void findFile()
{
string fName = "";
this.Dispatcher.Invoke(() => {
fName = inputFileName.Text;
});
var fType = ".txt";
var fileName = fName.Trim() + fType;
var file = Directory.GetFiles(@"C:\TestFolder\", fileName, SearchOption.AllDirectories).FirstOrDefault();
if (file == null) {
Console.WriteLine("File not found");
}
else {
Console.WriteLine("Found:" + file);
}
}
}
}
break
out of the foreach loop. – Philipphilipa