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:
o   One TextBox Control
o   One ComboBox Control
o   One ListBox Control
o   Two Button Control
Procedure:
Step 1: Arrange the mentioned controls on windows form as follows.

 
Figure 1
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();
          }
Listing 1
Step 3: Now, select Extension Type from ComboBox Control for Searching Files.
Figure 2
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();            }
          }
Listing 2
Step 5: Click the “Search” Button Control.
                                                                      
Step 6: If intended results found then the Name of that files are displayed in ListBox Control.
see Intended Result Section.
Intended Result:
Figure 3
Summary:
          In this article, we have seen how we to find the file names (of particular extension) from specified directory using C#.
Regards,
Mayur Dighe
http://ImmortalDotNet.blogspot.com
http://MayurDighe.wordpress.com