File Search By Extension in C#


Description:

The article demonstrates how to search the files from the specified path of directory based on which type of file are you finding. This can be useful further if you want to code for finding the files from sub-directories.

Basic Requirements:
  • One TextBox Control
  • One ComboBox Control
  • One ListBox Control
  • Two Button Control

Procedure:

Step 1: Arrange the mentioned controls on windows form as follows.

windows form

Step 2: Write Code section for accessing path as String.

    private void btnFolder_Click(object sender, EventArgs e)
    {    
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.ShowDialog();
        textBox1.Text = fbd.SelectedPath.ToString();
    }

Step 3: Now, select Extension Type from ComboBox Control for Searching Files.

extension type in C#

Step 4: Now, Code to search the desired files from given path.
 
    private void btnSearch_Click(object sender, EventArgs e)
    {
        String path = textBox1.Text;
        string[] files = Directory.GetFiles(@path);
        bool search = false; //returns true if file(s) found

        for
(int i = 0; i < files.Length; i++)
        {
            if (String.Compare(Path.GetExtension(files[i]), comboBox1.Text , true) == 0)
            {
                search = true;
                listBox1.Items.Add(files[i]);
            }
        }

        if
(search == false)
        {
            listBox1.Items.Add("Search is Complete. There are no results to display.");
            label1.Text = "Total Files: 0";
        }
        else
        { 
            label1.Text = "Total Files: " + listBox1.Items.Count.ToString(); }
        }
    }

Step 5: Click the “Search” Button Control.

Step 6: If intended results found then the Name of that files are displayed in ListBox Control.

Intended Result:

file search in csharp

Summary:

In this article, we have seen how we to find the file names (of particular extension) from specified directory using C#.