private void FileSearch(object mySearchedFile) { count++; SearchAttributes searchedFile = (SearchAttributes)mySearchedFile; string searchPath = searchedFile.SearchPath; string searchPattern = searchedFile.SearchPattern; lock (block) { try { DirectoryInfo dir = new DirectoryInfo(searchPath); FileInfo[] fileInfo; fileInfo = dir.GetFiles(searchPattern); foreach (var item in fileInfo) { founded++; listBox1.Invoke(new MyDelegate((s) => listBox1.Items.Add(s)), item.FullName); textBox2.Invoke(new MyDelegate((s) => textBox2.Text = s), "Please wait, searching... Founded " + founded + " files:"); } DirectoryInfo[] dirInfo = dir.GetDirectories(); foreach (var item in dirInfo) { if (item.Attributes.Equals(FileAttributes.System | FileAttributes.Hidden | FileAttributes.Directory)) { listBox1.Invoke(new MyDelegate((s) => listBox1.Items.Add(s)), "The process failed: " + item.FullName + " " + item.Attributes); continue; } SearchAttributes search = new SearchAttributes { SearchPath = item.FullName.ToString(), SearchPattern = textBox1.Text }; FileSearch(search); } } catch (Exception e) { textBox2.Invoke(new MyDelegate((s) => textBox2.Text = s), "The process failed: " + e.Message); // Add all errors to the same list box where the list of found files. listBox1.Invoke(new MyDelegate((s) => listBox1.Items.Add(s)), "The process failed: " + e.Message); } } count--; if (count == 0) { textBox2.Invoke(new MyDelegate((s) => textBox2.Text = s), "Founded " + founded + " files:"); MessageBox.Show("Founded " + founded + " files", "Search finished!"); } }
private void buttonSearch_Click(object sender, EventArgs e) { listBox1.Items.Clear(); textBox2.Text = "Please wait, searching..."; for (int i = 0; i < checkedListBox1.Items.Count; i++) { if (checkedListBox1.GetItemChecked(i)) { SearchAttributes search = new SearchAttributes { SearchPath = checkedListBox1.Items[i].ToString(), SearchPattern = textBox1.Text }; Thread th = new Thread(FileSearch); // run the search in the new stream so that the search window does not hang th.Start(search); } } }