Friday, March 29, 2013

c#: Get all the files in a folder

Get all the files in a folder
private static List files = new List();
static void FullDirList(DirectoryInfo dir, string searchPattern)
{
 // Console.WriteLine("Directory {0}", dir.FullName);
 // list the files
 try
 {
  foreach (FileInfo f in dir.GetFiles(searchPattern))
  {
   //Console.WriteLine("File {0}", f.FullName);
   files.Add(f);
  }
 }
 catch
 {
  Console.WriteLine("Directory {0}  \n could not be accessed!!!!", dir.FullName);
  return;  // We alredy got an error trying to access dir so dont try to access it again
 }

 // process each directory
 // If I have been able to see the files in the directory I should also be able 
 // to look at its directories so I dont think I should place this in a try catch block
 foreach (DirectoryInfo d in dir.GetDirectories())
 {                
  FullDirList(d, searchPattern);
 }

}

No comments:

Post a Comment