Since you did not specify a language or a framework, I'll assume you're using C#. You said:
I'm trying to have my program search to see if a file exists. The concept is that if the file exists, it will be launched.
Here's a short snippet that will do what you've asked.
string path = @"C:\path\to\file";
if (File.Exists(path))
{
Process p = new Process();
p.StartInfo.FileName = path; // launches the default application for this file
p.Start();
}
This is slightly simplistic: p.Start() could throw exceptions for a number of reasons. Additionally, you have little control over which application opens the file - it's entirely up to the user's registry. For example, if the user selects an HTML file to open, some users will see the file opened using Internet Explorer while other users will have Firefox installed, and so Firefox will be used to view the file.
Update:
Normally, I search for files using the following:
string[] matches = Directory.GetFiles(@"C:\", "*.txt");
Which returns all the paths to all the files on the C:\
drive ending with .txt
. Of course, your search pattern will be different.
If the call to Directory.GetFiles( ) (or whatever you're using - you did not specify) takes a long time, then yes, using a BackgroundWorker is a good approach. Here's how you might do it. In the constructor of a class (you might choose to call it SearchFiles
):
string searchPattern;
string searchDirectory;
BackgroundWorker worker;
string[] matches;
/// <summary>
/// Constructs a new SearchFiles object.
/// </summary>
public SearchFiles(string pattern, string directory)
{
searchPattern = pattern;
searchDirectory = directory;
worker = new BackgroundWorker();
worker.DoWork += FindFiles;
worker.RunWorkerCompleted += FindFilesCompleted;
worker.RunWorkerAsync();
}
void FindFilesCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error == null)
{
// matches should contain all the 'found' files.
// you should fire an event to notify the caller of the results
}
}
void FindFiles(object sender, DoWorkEventArgs e)
{
// this is the code that takes a long time to execute, so it's
// in the DoWork event handler.
matches = System.IO.Directory.GetFiles(searchDirectory,searchPattern);
}
I hope this answers your question!