Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there everyone,

I am trying to search for files in a directory. I want to give the method a directory to search in and the name of the files I want and it must look in the directory and get me all the files with that name. I am currently using:

SearchedFiles = Directory.GetFiles(str_Directory, str_Name, SearchOption.AllDirectories);


where Searched files is an array of strings and the Directory.GetFiles method returns an array with all the file names found.

The problem is that if there are directories that are read protected, the method aborts and throws an exception "UnauthorizedAccessException".

Is there a way to search for files and just ignore all the directories that can't be read, instead of the method aborting and throwing the exception. It could also help if someone knows of an better search Method.

Thanks
Grimes
Posted
Updated 20-Sep-10 4:01am
v2
Comments
demouser743 20-Sep-10 10:23am    
For what type of files you are searching for.

You can use a partially recursive method. (partially because in an ideal case the recursive part is handled by the framework using "AllDirectories")

Rather than getting all the files on one call build them up.

so the method might be something like

 void RecursiveFileFinder(string path, List<string> collection)
{
   DirectoryInfo dInfo = null;
   try
   {
        dInfo = new DirectoryInfo(path);
   }
   catch(UnauthorizedAccessException)
   {
       //This is the directory that is causing the failure
       //No need to process this directory
       return collection;
   }  
try //Process all sub dirs if possible
{
  string[] foundFiles = dInfo.GetFiles(str_Name,SearchOption.AllDirectories);
    collection.AddRange(foundFiles);
}
catch(UnauthorizedAccessException)
{
      //Call for each dir since we don't know which failed
      var subDirs = dInfo.GetDirectories();
      foreach(var subDir in subDirs)
      {
          RecursiveFileFinder(string path, List<string> collection);
      }
}
}
</string></string>


I havn't tested it but I had to do something similar to this before and it resolved the issue.
 
Share this answer
 
v2
If your search method is of the 'usual' recursive type, you can catch the problematic exceptions and ignore them.

Something like:
C#
try
{
    files = Directory.GetFiles(directory, search);
}
catch (UnauthorizedAccessException)
{
    return;
}
catch (DirectoryNotFoundException)
{
    return;
}

You should probably add a third catch for other exceptions, displaying them (MessageBox, Console...whatever) so that you can then decide whether to add a specific exception handler for them.
 
Share this answer
 
Thanks for everyones help. I thought that there would be an easy method to use to fix the problem, but it seems that I had to write my own recursive search function.

My method was based on Collin's code, so thanx for the help. Here is the code that I wrote:

public static ArrayList GetFiles(string SearchPath, string FileName)
        {
            //Temporarily stores the files found
            ArrayList TempFileNames = new ArrayList();
            try
            {
                //get all the sub directories
                DirectoryInfo DirInfo = new DirectoryInfo(SearchPath);
                DirectoryInfo[] SubDirs = DirInfo.GetDirectories();
                for (int i = 0; i < SubDirs.Length; i++)
                {
                    //check inside each sub-dir (Recursion)                   
                    TempFileNames.AddRange(GetFiles(SubDirs[i].FullName, FileName));
                }
                //after searching sub-dirs look in the current dir
                TempFileNames.AddRange(Directory.GetFiles(SearchPath, FileName, SearchOption.TopDirectoryOnly));
            }
            //Handle exceptions for unreadable files
            catch (UnauthorizedAccessException ex)
            { 
                return TempFileNames;
            }
            catch (DirectoryNotFoundException ex)
            {
                return TempFileNames;
            }
            return TempFileNames;
        }


I have tested it and it works and ignores the unreadable directories as it should. Hopefully this helps the next guy ;)
 
Share this answer
 
A sample code to retrieve the text files with some name

string strFileEntries = Directory.GetFiles(strFilePath, "FileHeader*.txt");



This will give all the files with txt as extension.
 
Share this answer
 
v2
Comments
Grimes 20-Sep-10 10:36am    
The problem isn't that I can't find files. The code I am using is finding the correct files, it is just that if there are read-protected directories in the folder I am searching in, the search fails with "UnauthorizedAccessException"

I want to know if there is a way to ignore these read-protected folders.
Grimes 20-Sep-10 10:37am    
..or a way to ignore these UnauthorizedAccessException exceptions and continue searching in the other folders...
demouser743 20-Sep-10 10:46am    
Where your files exists are you placing in any seperate folder or saving in any other
Grimes 20-Sep-10 10:53am    
The program I am writing should look for certain files, and should be able to search complete hard drives, removable drives or network locations. So it frequently encounters protected directories.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900