Jump to content


Check out our Community Blogs





- - - - -

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

  Posted by Barnsite, 07 December 2012 · 902 views

programming
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;
}
}



http://feeds.wordpre...dpress.com/510/ Posted Image

Source

  • 0