Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

Learning never ends, everyday we learn at least one thing. This applies to both our personal and programming stuffs. Today I learnt coding stuff which I wanted to build in one of my application. Thought to share the same in case you need, this will help you.

 

Did you ever think about building an application to provide a directory or file search functionality to the end user? .NET provides you that APIs which we will discuss in this post today.

 

 

Do you know that the System.IO.Directory class provides you APIs to search for a particular file or directory in a given path? If you are looking for a piece of code to programmatically implement a searching mechanism in user’s or server’s local drive, this post will guide you to build the same easily. Now, it’s time for you to explore the .NET API and search with different parameters from your application.

 

To get started with this, let us create a simple Console based application. We will take this project so that learning will be easier than the other project templates.

 

How to Search for File or Folder Programmatically? (www.kunal-chowdhury.com)

 

 

Search for Directory

Let’s begin with creating a method named EnumerateDirectories() which when called will list out all the folder/directories under the path that we mention. For our demo, we will choose “C:\” as the root directory and we will iterate through all the directories present under this path.

 

This operation may throw “UnauthorizedAccessException” and hence make sure to wrap them under a try{} catch{} block. Let us write a LINQ query and call the Directory.EnumerateDirectories(…) method and create a collection of anonymous object with the Path property. The Path property will host the path of the directory.

 

Here is the code snippet for your reference:

 

private static void EnumerateDirectories()
{
    try
    {
        // Get the list of all folders matching the pattern in all directories under the path
        var listOfFolders = from folderPath in Directory.EnumerateDirectories(@"C:\", 
                                        SEARCH_PATTERN, SearchOption.AllDirectories)
                            select new
                            {
                                Path = folderPath
                            };
 
        foreach (var folderItem in listOfFolders)
        {
            Console.WriteLine(folderItem.Path);
        }
    }
    catch (UnauthorizedAccessException)
    {
    }
}

 

 

If you want to search for a specific directory, mention the same under the SEARCH_PATTERN key and in case you want to search for all folders, use wild search pattern.

 

Once you execute the said code, you will see a console window with the directory listing similar to the snapshot as shown below. If you encounter any UnauthorizedAccessException, the above code will return and will not execute further. So in such case, you have to handle in properly.

 

Directory Search Result in Root Drive

 

 

Search for File

In similar way, let us create another method named “EnumerateFiles” and this time, instead of calling the API method named Directory.EnumerateDirectories(…), we will call Directory.EnumerateFiles(…) inside the LINQ query and create a collection of file path that matches the SEARCH_PATTERN.

 

As you might face UnauthorizedAccessException, wrap the piece of code in a try{} catch{} block to handle the exception properly. Here is the piece of code for your reference:

 

private static void EnumerateFiles()
{
    try
    {
        // Get the list of all files matching the pattern in all directories under the path
        var listOfFiles = from file in Directory.EnumerateFiles(@"C:\", 
                                    SEARCH_PATTERN, SearchOption.AllDirectories)
                          select new
                          {
                              File = file
                          };
 
        foreach (var fileItem in listOfFiles)
        {
            Console.WriteLine(fileItem.File);
        }
    }
    catch (UnauthorizedAccessException)
    {
    }
}

 

Once you run the above code, you will see the console window with something similar to this. As the UnauthorizedAccessException will not allow you to proceed further, you have to handle it properly and run the execution step properly.

 

File Search Result in Directory

 

 

I hope, this chunk of code will help you someday in some case and hence, bookmark it for future reference. If you landed to this page by searching online for similar kind of code, please drop a line below with your problem and how this helped you.

 

I am available on Twitter and Facebook. Did you already connect with me? If not, connect with me for any kind of discussion and getting different technology article updates from my site. Happy Coding!!!

Have a question? Or, a comment? Let's Discuss it below...

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.