How to Search files in directory in C#
By FoxLearn 11/21/2024 1:49:44 AM 11.34K
How to search file in directory and subdirectories in C#
To play the demo, You can drag and drop the textbox, label, button, progress bar and listview controls from your Visual Studio toolbox to your windows forms application, then design a simple UI that allows you to select the directory, enter the file name and use c# get all files in directory and subdirectories as shown below.
You can use BackgroundWorker control to process data, by dragging the BackgroundWorker control from the visual studio to your winform, then set WorkerReportsProgress and WorkerSupportsCancel properties to True.
Create the ScanDirectory allow you to get specific file from directory in c# as shown below.
// c# directory search public void ScanDirectory(string directory, string pattern) { // c# search files in folder and subfolders foreach (var file in Directory.GetFiles(directory)) { if (backgroundWorker1.CancellationPending) return; lblPercentage.Invoke((Action)(() => lblStatus.Text = file)); if (file.Contains(pattern)) AddItemToListView(file); } foreach (var dir in Directory.GetDirectories(directory)) ScanDirectory(dir, pattern); }
You can also use the GetFiles
// Search for files string[] files = Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
The lblPercentage label will show percent complete. You should call the Invoke method to update ui from background thead (backgroundworker), to make cross-thread calls to windows forms controls. This is the best way to update the GUI from another thread in c# windows forms application.
Next, Create the AddItemToListView method to add search files in folder to the ListView control.
// c# add item to listview control public void AddItemToListView(string file) { FileInfo fi = new FileInfo(file); listView1.Invoke((Action)(() => { var icon = Icon.ExtractAssociatedIcon(file); string key = Path.GetExtension(file); imageList1.Images.Add(key, icon.ToBitmap()); ListViewItem item = new ListViewItem(fi.Name, key); item.SubItems.Add(fi.DirectoryName); item.SubItems.Add(Math.Ceiling(fi.Length / 1024f).ToString("0 KB")); listView1.BeginUpdate(); listView1.Items.Add(item); listView1.EndUpdate(); })); }
The FileInfo class allows you to get information about files. you can also use the ExtractAssociatedIcon method to extract an icon of files then add to the ImageList control.
Add code to browse the directories, by updating the selected path to the textbox control
private void btnBrowse_Click(object sender, EventArgs e) { using (FolderBrowserDialog fbd = new FolderBrowserDialog()) { if (fbd.ShowDialog() == DialogResult.OK) txtPath.Text = fbd.SelectedPath; } }
Add the DoWork event handler to the BackgroundWorker control as the following c# code.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string[] directories = Directory.GetDirectories(txtPath.Text); float length = directories.Length; progressBar1.Invoke((Action)(() => progressBar1.Maximum = directories.Length)); ScanDirectory(txtPath.Text, txtFileName.Text); for (int i = 0; i < directories.Length; i++) { backgroundWorker1.ReportProgress((int)(i / length * 100)); ScanDirectory(directories[i], txtFileName.Text); } backgroundWorker1.ReportProgress(100); }
Add the ProgressChanged event handler to the BackgoundWorker control, it helps you update the progress bar control and the percentage completed.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (!backgroundWorker1.CancellationPending) { lblPercentage.Text = e.ProgressPercentage + "%"; progressBar1.PerformStep(); } }
Add the RunWorkerCompleted event handler to the BackgroundWorker control allows you to update the status completed.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { lblStatus.Text = String.Format("Found {0} item.", listView1.Items.Count); if (progressBar1.Value < progressBar1.Maximum) lblStatus.Text = "Stop searching..."; btnSearch.Text = "Search"; }
Finally, Double click on Search button, then add a click event handler to the search button as the following c# code.
private void btnSearch_Click(object sender, EventArgs e) { if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync(); else { progressBar1.Value = progressBar1.Minimum; btnSearch.Text = "Stop"; listView1.Items.Clear(); backgroundWorker1.RunWorkerAsync(); } }
Press F5 to run your application, then select the path and enter the file name to find the file by name in c#.
In this example, you have a Windows Forms application with a TextBox
for showing the directory path by selecting the path and a TextBox
for entering the search pattern (e.g., "*.txt" for all text files). When the user clicks a button (btnSearch
), it triggers the btnSearch_Click
event handler.
Inside the event handler, it first clears any previous search results from the listView1
. Then it retrieves the directory path and search pattern from the text boxes. It searches for files matching the search pattern in the specified directory and its subdirectories using Directory.GetFiles()
. Finally, it displays the found files in the listView1
.