I have the following code where I have a single TextBox
which the user uses for entering a file name. What I want to happen is that when the user types the file name the search won't happen until he/she stops/pauses typing, similar to the way searches work in windows explorer, Outlook etc.
With the code below I'm getting the following error...
InvalidOperationException was unhandled by user code
An exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll but was not handled in user code
Additional information: The calling thread cannot access this object because a different thread owns it.
Error points to line var fName = inputFileName.Text;
in the findFile()
method.
Any idea what could be wrong?
CODE:
namespace FileFinder
{
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)
{
timer.Stop();
timer.Start();
}
public void TimerEvent(object source, ElapsedEventArgs e)
{
timer.Stop();
findFile();
}
private void findFile()
{
var fType = ".pdf";
var fName = inputFileName.Text; // error points to this line
var fileName = fName.Trim() + fType;
var file = Directory.GetFiles(@"C:\SomeFolder\", fileName, SearchOption.AllDirectories).FirstOrDefault();
if (file == null) {
myButton.Background = Brushes.Red;
}
else {
myButton.Background = Brushes.Green;
}
}
}
}