Search Specified Type Of File In C#

Introduction

If you need to determine the location of a specified file type in all directories of your computer, then this article is very helpful for that.

Now, first, I determine all the directories of your system using a C# program.

Example

This example simply shows the drive names of all drives in the computer and also counts them.

using System;
using System.IO;
namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            DriveInfo[] TotalDrives = DriveInfo.GetDrives();
            foreach (DriveInfo drvinfo in TotalDrives)
            {
                Console.WriteLine("Drive {0}", drvinfo.Name);
                count++;
            }
            Console.WriteLine("Total number of Drives = " + count);
            Console.ReadKey();
        }
    }
}

Output

get-drives

The purpose of the code above is basically to use it in the following code because when you want to search for a specified type of file in all drives of your computers, you need the name of each.

Now, I am writing code that displays all the specified types of file name with the path. Basically, this code only returns the file name with a path whose extension is "*.*". You can also change the specified type as needed. Example This example returns all the specified types of file names with paths from all drives of your computer.

using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication9
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in allDrives)
            {
                string driveName = drive.Name.ToString();
                var filenames = Directory.GetFiles(driveName, "*.*", SearchOption.TopDirectoryOnly);
                foreach (string filename in filenames)
                {
                    MessageBox.Show(filename);
                }
            }
        }
    }
}

Output

"get-specified-type-of-files


Similar Articles