Windows Forms: Search files in directory in C#

This tutorial shows you how to search file in directory and subdirectories in C#.NET Windows Forms Application.

To play the demo, you can drag 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.

c# search files in directory and subdirectories

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.

public void ScanDirectory(string directory, string pattern)
    foreach (var file in Directory.GetFiles(directory))
        if (backgroundWorker1.CancellationPending)
        lblPercentage.Invoke((Action)(() => lblStatus.Text = file));
        if (file.Contains(pattern))
    foreach (var dir in Directory.GetDirectories(directory))
        ScanDirectory(dir, pattern);

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.

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(Math.Ceiling(fi.Length / 1024f).ToString("0 KB"));

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);

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 + "%";

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)
        progressBar1.Value = progressBar1.Minimum;
        btnSearch.Text = "Stop";

Press F5 to run your application, then select the path and enter the file name to find the file by name in c#.