Searching and Listing Files of Selected Drive in WPF

Introduction

First let me introduce what this article does. This article introduces how to search the files of your drive and list the results in a Data Grid View. Let me explain step-by-step how to do that.

First create an Entity (Simple CLR class) to contain the folder (Directory) details such as directory name, Full Name, Is Searched and so on. You might ask, if there is a default class named Directory Info already available in the .Net framework and we inherit from that rather than create all new properties and can instead add a few properties, why I have used this class. This solution can answer your question, and we will discuss it later.

The following is the code of the entity class named "My Folder".

Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SearchingFileInWPF
{
    public class MyFolder
    {
        public string Name { get; set; }
        public string FullName { get; set; }
        public bool Searched { get; set; }

        public MyFolder()
        {
            this.Searched = false;
        }
    }
}

Create another entity named "My File" to contain the folder details, such as name, full name, file type and so on. Your question above might come in your mind, because both the FileInfo and DirectoryInfo classes are sealed and cannot be inheritable.

The following is the code of the "My File" class.

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SearchingFileInWPF
{
    public class MyFile
    {
        public string Name { get; set; }
        public string FullName { get; set; }
        public long Size { get; set; }
        public string Type { get; set; }
        public DateTime CreateDate { get; set; }
    }
}

 

Then add one text block control into your Windows form and set the properties as in the following code:

<TextBlock Height="31" HorizontalAlignment="Stretch" Margin="0,151,0,0" Name="textBlock1" Text="Search by any or all of the criteria" VerticalAlignment="Top" Width="Auto" TextTrimming="None" TextWrapping="Wrap" FontWeight="Bold" FontSize="12" />

Again add one label control and set the properties as in the following:

<Label Content="All or Part of the File Name" Height="28" HorizontalAlignment="Left" Margin="0,188,0,0" Name="label1" VerticalAlignment="Top" />

Add a Text box for entering the file name to search for and set the properties as in the following:

<TextBox Height="23" HorizontalAlignment="Stretch" Margin="0,209,0,0" Name="txtSearch" VerticalAlignment="Top" Width="Auto" />

Again add a label control and set the properties as in the following:

<Label Content="Look In" Height="28" HorizontalAlignment="Left" Margin="0,238,0,0" Name="label2" VerticalAlignment="Top" />

Add a Combo Box to list the drives available in your system and set the properties as in the following:

<ComboBox Height="23" HorizontalAlignment="Stretch" Margin="0,257,0,0" Name="cmbDrive" VerticalAlignment="Top" Width="Auto" />

Add a button control to start the search action as in the following:

<Button Content="Search" Height="23" HorizontalAlignment="Right" Margin="66,286,0,0" Name="btnSearch" VerticalAlignment="Top" Width="75" Click="btnSearch_Click" />

In the windows load event bind the drives available in your system with your Combo Box. The code that binds drives with the Combo Box is given below.

Code


this.cmbDrive.ItemsSource = DriveInfo.GetDrives().Where(dr => dr.IsReady == true).ToList();
this.cmbDrive.DisplayMemberPath = "Name";
this.cmbDrive.SelectedValuePath = "Name";


On the click event of the button control write the following code to start the search action.

Code

 if (this.cmbDrive.SelectedValue == null)
                return;

//the list of myfolder that contains folder information

List<MyFolder> FolderList = new List<MyFolder>();
//create the object of directoryinfo
DirectoryInfo DF = new DirectoryInfo(this.cmbDrive.SelectedValue.ToString());
          
if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
{
    // search the file and available in the directory based the criteria
    foreach (FileInfo FI in DF.GetFiles(this.txtSearch.Text.Trim()))
    {
        this.DGVFileList.Items.Add(new MyFile() { Name = FI.Name, FullName = FI.FullName, Size = FI.Length, Type = FI.Extension, CreateDate = FI.CreationTime });
    }
}
else
{
    foreach (FileInfo FI in DF.GetFiles())
    {
        this.DGVFileList.Items.Add(new MyFile() { Name = FI.Name, FullName = FI.FullName, Size = FI.Length, Type = FI.Extension, CreateDate = FI.CreationTime });
    }
}

//retrives the directory(folder) information from your drive
foreach (DirectoryInfo DIR in DF.GetDirectories())
{
    //check whether the folder is accessable or not
    if (!DIR.Attributes.ToString().Contains("Hidden"))
    {
        // search the file and available in the directory based the criteria
        if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
        {
            foreach (FileInfo FI in DIR.GetFiles(this.txtSearch.Text.Trim()))
            {
                this.DGVFileList.Items.Add(new MyFile() { Name = FI.Name, FullName = FI.FullName, Size = FI.Length, Type = FI.Extension, CreateDate = FI.CreationTime });
            }
        }
        else
        {
            // search the file and available in the directory
            foreach (FileInfo FI in DIR.GetFiles())
            {
                this.DGVFileList.Items.Add(new MyFile() { Name = FI.Name, FullName = FI.FullName, Size = FI.Length, Type = FI.Extension, CreateDate = FI.CreationTime });
            }
        }
        //adds the folder into the list and set the searched property to fals
        FolderList.Add(new MyFolder() { Name = DIR.Name, FullName = DIR.FullName, Searched = false });
    }
}
while (FolderList.Where(fl => fl.Searched == false).Count() > 0)
{
    //retrives the folders whome files are not searched
    foreach (MyFolder MF in FolderList.Where(fl => fl.Searched == false).ToList())
    {
        DirectoryInfo DIR = new DirectoryInfo(MF.FullName);
        MF.Searched = true;
        if (!DIR.Attributes.ToString().Contains("Hidden"))
        {
            if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
            {
                foreach (FileInfo FI in DIR.GetFiles(this.txtSearch.Text.Trim()))
                {
                    this.DGVFileList.Items.Add(new MyFile() { Name = FI.Name, FullName = FI.FullName, Size = FI.Length, Type = FI.Extension, CreateDate = FI.CreationTime });
                }
            }
        else
        {
            foreach (FileInfo FI in DIR.GetFiles())
            {
                this.DGVFileList.Items.Add(new MyFile() { Name = FI.Name, FullName = FI.FullName, Size = FI.Length, Type = FI.Extension, CreateDate = FI.CreationTime });
            }
        }
        foreach (DirectoryInfo DR in DIR.GetDirectories())
        {
            FolderList.Add(new MyFolder() { Name = DR.Name, FullName = DR.FullName, Searched = false });
        }
    }
}


For any query kindly feel free to ask.

Thanks