How to Search for File or Folder Programmatically?


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!!!


4 comments

  1. First time seeing your blog and impreed alot. Great job.
    how to subscribe on email for each new posts

    ReplyDelete
    Replies
    1. Thank you Krish for visiting my blog and providing feedback. You are welcome here. To subscribe to the "Email" got to the top right corner of the site, there you will find a green subscription box.

      Regards,
      Kunal

      Delete
  2. Could you please give more explanation about this(I'm new to .Net)
    BTW nice blog so far... :)

    ReplyDelete
  3. Thanks very much for this blog. Am just writting an application that search my local drive for a particular file, but the problem am facing is how to properly handle unauthorizeaccess exception, unfortunately, this blog does not go deep into it. I wrap the directory.enumeratefiles inside a try....catch block, but whenever the searching reach a subdirectory that throw an unaithorizeaccess exception, the code would not search the other subdirectory again and exit the current directory. This lead to incomplete enumeration of files and directories. Pls, if there is solution kindly provode me with answer. My mailbox is solixzsystem@gmail.com
    Thanks.

    ReplyDelete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top