Find all Subdirectories from a given path using C# – With Error Handler

In my earlier post () I showed how you can iterate through folders and add the folder names to a list (lstDirs). The problem with this code was that if you encountered a folder you didn’t have access to it all fell over. Below I’ve added a function to test the folder access (canReadDir()), if the folder is inaccessible the path is added to lstFailed and reading is skipped for this folder:

private void loadSubDirs(string sPath)
{
    if(canReadDir(sPath)
    {
        DirectoryInfo dInfo = new DirectoryInfo(sPath);
        DirectoryInfo[] subDirs = dInfo.GetDirectories();

        foreach (DirectoryInfo dir in subDirs)
        {
            lstDirs.Items.Add(dir.FullName);
            //call loadSubDirs with current dir name
            loadSubDirs(dir.FullName);
        }
    }
    else
    {
       lstFailed.Items.Add(sPath);
    }
{


private bool canReadDir(string sPath)
{
   DirectoryInfo dInfo = new DirectoryInfo(sPath);
   try
   {
      //try to get directories if fails will go to catch
      DirectoryInfo[] subDirs = dInfo.GetDirectories();
      return true;
   }
   catch
   {
      return false;
   }
}


Advertisements
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s