Click here to Skip to main content
15,899,937 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying to build a directory recursive search using two different approaches; which starts from a given directory path. I've tried two different approaches of doing a recursive file search and still comes up with many errors. Is there a way of ignoring the errors (so to speak) and just carry on with the recursive search?
I've also been looking at different examples for ideas on how to get it to work. But still no success.
Is there anyone whom could help me fix these problems of avoiding/ignoring hidden sysem files, hidden system directories, and all other system/hidden stuff, and especially the "UnauthorizedAccessException" error. One approach use to run so-so if there is no system stuff to get in the way of the recursive search.

Below is what I have been working with. Is it possible to get both approaches running.

Thanks though.

What I have tried:

C#
public EnumerationOptions EnumOptn { get; private set; }
public EnumerationOptions EnumOptn1 { get; private set; }

// Approach one:
   EnumOptn1.EnumerateDeep = true;
    var myDir = "c:\\users\\auror\\";     /////  RecurseSubdirectories = true -- nope, can't find. 
    var dirInfo = new DirectoryInfo(myDir);
    String[] dirsx = dirInfo.EnumerateDirectories("*", new EnumerationOptions(  { EnumOptn1.EnumerateDeep }) );
    foreach (var xfiles in dirsx)
    {
        string casefullpathname = Path.GetFullPath(xfiles).ToLower();
        string casestrg = Path.GetFileNameWithoutExtension(xfiles).ToLower();
        string caseextentionstrg = Path.GetExtension(xfiles).ToLower();
        Console.WriteLine(casefullpathname);
        ///                               
          myfilelistBox1.Items.Add(casefullpathname);
        ///                            }
    Console.ReadLine();
  }

//Approach 2:

   var EnumOptn = new EnumerationOptions { EnumerateDeep = true };
    ////           EnumerateFiles(String, String, EnumerationOptions) has the EnumerationOptions.RecurseSubdirectories = true
    //// RecurseSubdirectories = true -- should be using it.
    ///                          System.IO.EnumerationOptions enumerationOptions
    String[] myfiles = Directory.EnumerateFiles(rootpath, "*.dll", new EnumOptn);
    foreach (var file in myfiles)
    {
        Console.WriteLine(file);
    }
    Console.ReadLine();
Posted
Updated 6-May-21 22:23pm
v3
Comments
Member 15028314 5-May-21 21:36pm    
Please provide solid working examples, to support your suggestion(s).

Put the search inside a try/catch block. You can then check if it throws the UnauthorizedAccessException and ignore it. See Directory.EnumerateDirectories Method (System.IO) | Microsoft Docs[^].
 
Share this answer
 
The only way to solve this problem is to create your own directory/file enumeration methods as the library version were designed such that they will fail if any hidden or unauthorized files or directories are encountered.
 
Share this answer
 
Comments
Member 15028314 6-May-21 16:24pm    
Again, I'm working on two approaches that I'm on. Each approach has an error; that I do not understand. Error #'s: 1501 and 1503.
I'm to get both approaches working and then determine which one is best to use. So, which one is best to use??

Here they are:

var EnumOptns = new EnumerationOptions();

Approach one:
var dirInfo = new DirectoryInfo(searchDirectory);
String[] dirsx = dirInfo.EnumerateDirectories(searchstring, EnumOptns);
///// "EnumOptns" is underlined only.
///// With Error CS1503 Argument 2: cannot convert from 'WindowsFormsApp10T.EnumerationOptions'
foreach (String stfs in dirsx) {
---------------------------
Approach two:
String[] thefiles = System.IO.DirectoryInfo.EnumerateFiles(searchDirectory, searchstring, EnumOptns);
//// "EnumerateFiles" is underlined only. There are 3 arguments present.
//// With Error CS1501 No overload for method 'EnumerateFiles' takes 3 arguments.
foreach (String stfs in thefiles) {
------------------------------

var EnumOptns = new EnumerationOptions();

I do have an EnumerationOptions.cs file.
Contents:.....
namespace WindowsFormsApp10T
{
/////public static System.Collections.Generic.IEnumerable<string> EnumerateFiles();

internal class EnumerationOptions
{
public EnumerationOptions()
{
RecurseSubdirectories = true;
IgnoreInaccessible = true;
}
public bool IgnoreInaccessible { get; set; }

public bool RecurseSubdirectories { get; set; }
}
}
=======================

What am I doing wrong?, I know I'm close though.
Can anyone help me get these two approaches working? .
Thanks though.
I mentioned before that you would need to code your own directory enumerations methods as the MS methods will fail if they encounter an error and will not continue the enumeration and there is nothing you can do about it

If I was you I would just forget that the MS methods exist.

See below a simple program that will enumerate through the folders/files.

public static void Main(string[] args)
{
    MyGetDirectories("C:\\Users", "*.*");
}


public static void MyGetDirectories(string folderPath, string fileFilter)
{
    string[] directories = Directory.GetDirectories(folderPath);

    foreach (string directory in directories)
    {
        try
        {
            MyGetDirectories(directory, fileFilter);

            Console.WriteLine($"{directory}");
        }
        catch(UnauthorizedAccessException)
        {
            Console.WriteLine($"Cannot access directory {directory}, skipping diirectory.");
        }
        catch (Exception)
        {
            // Catch remaining exceptions and ignore for this demo.
        }
    }

    string[] files = Directory.GetFiles(folderPath, fileFilter);

    foreach (string file in files)
    {
        try
        {
            FileInfo fileInfo = new FileInfo(file);

            Console.WriteLine($"File Name = {file} -     File Size = {fileInfo.Length}");

        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine($"Cannot access file information {file}.");
        }
        catch (Exception)
        {
            // Catch all remaining exceptions and ignore for this demo
        }
    }
}
 
Share this answer
 
v2
Comments
Louis T Klauder Jr 29-Nov-22 18:06pm    
unfortunately, "Directory.GetFiles(folderPath, fileFilter);" throws an UnauthorizedAccessException if the subfolder 'System Volume Information' is present.

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