I need some help. Right now i have done a file search that will search my entire hard drive and it works. Here are the two methods that does it.
public void SearchFileRecursiveNonMultithreaded()
{
//Search files multiple drive
string[] drives = Environment.GetLogicalDrives();
foreach (string drive in drives)
{
if (GetDriveType(drive).ToString().CompareTo("DRIVE_FIXED") == 0)
{
DriveInfo driveInfo = new DriveInfo(drive);
if (driveInfo.IsReady)
{
System.IO.DirectoryInfo rootDirectory = driveInfo.RootDirectory;
RecursiveFileSearch(rootDirectory);
}
}
}
MessageBox.Show(files.Count.ToString());
}
public void RecursiveFileSearch(DirectoryInfo root)
{
DirectoryInfo[] subDirectory;
try
{
//private List<FileInfo> files = new List<FileInfo>() is declared above
files.AddRange(root.GetFiles(searchString.Text, SearchOption.TopDirectoryOnly));
}
catch (Exception)
{
}
try
{
// Now find all the subdirectories under this directory.
subDirectory = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirectory)
{
// Resursive call will be performed for each subdirectory.
RecursiveFileSearch(dirInfo);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Right now i am trying to implement a parallel search to make the search faster. I tried several procedures to get this to work. Tried to use backgroundworker as well as threads but have problems with it and it is very difficult to debug to know what is wrong ? Can someone let me know the approach to implement a parrallel search. The step will do i will go and figure out on my own. Any help provided will be greatly apperciated.
First, as somebody else pointed out, it’s unlikely that using multiple threads will speed things up when you’re searching just one drive. The vast majority of your time is spent waiting for the disk head to move to where it needs to be, and it can only be in one place at a time. Using multiple threads here is wasted effort, and has a high likelihood of actually making your program slower.
Second, you can simplify your code by just calling Directory.EnumerateFiles. If you want to search multiple drives concurrently, simply start multiple
BackgroundWorkerinstances, each usingEnumerateFilesto search a different drive.Note, however, that
EnumerateFileswill throw an exception (as will your code) if it runs across directory permissions problems, which aren’t uncommon when searching an entire drive. If that’s a problem (and it likely will be), then you have to write your own directory searcher. One such is in the answer to this question.