Solved

C# Scan Directories recusively with given Maxdepth

Posted on 2009-05-10
6
844 Views
Last Modified: 2013-12-17
I have the followin class, scanning all Subdirectories of a given Directory. I would like to add a new parameter "Maxdepth", so it only scans with a maximum Depth of the given param

e.g.

Dir 1
  Dir 1.1
    Dir 1.1.1
      Dir 1.1.1.1 -> should not be scanned

How can I count the actual depth and go to the next directory?

Actualy I have 3 Arguments:
1. List with Include Paths
2. List with exclude paths
3. Boolean for recursive scan

The 4. Parameter should be the Maxdepth
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Management;

using System.Xml.Linq;

using System.IO;

using System.Security;

using System.Security.AccessControl;

using System.Security.Principal;

using System.DirectoryServices.ActiveDirectory;

using System.DirectoryServices;

using System.Windows.Forms;
 

namespace DirectoryScan

{

    public class ACL

    {
 

        /// <summary>

        /// Variables

        /// </summary>

        private String mDirectoryName       = string.Empty;

        private String mAccountName         = string.Empty;

        private String mTyp                 = string.Empty;

        private String mRights              = string.Empty;

        private String mInherited           = string.Empty;

        private String mInheritanceFlags    = string.Empty;

        private String mPropagationFlags    = string.Empty;

        private int mDirectoryCount         = 0;
 

        /// <summary>

        /// Default Constructor

        /// </summary>

        public ACL()

        {

        

        }
 

        public static Dictionary<String, List<ACL>> GetACLInformation(List<Object> includePath, List<Object> excludePath, bool recursive)

        {
 

            // Create Collection Instance

            Dictionary<String,List<ACL>> aclSet = new Dictionary<String,List<ACL>>();
 

            foreach (String driveInfo in includePath)

            {

                // Call recursive private Method

                readDir(new DirectoryInfo(driveInfo), excludePath, aclSet, recursive);

            }
 

            // Return Dictionary

            return new Dictionary<string,List<ACL>>(aclSet);
 

        }
 
 

        private static void readDir(DirectoryInfo directory, List<Object> excludePath, Dictionary<String,List<ACL>> lAclSet, bool recursive)

        {
 

            try

            {
 

                // Check exclude Paths

                if (! excludePath.Contains(directory.FullName.ToString().Trim()))

                {
 

                    // Save Directory Name

                    String dirName = directory.FullName.ToString();
 

                    // Count Subfolders

                    DirectoryInfo[] subDirs = directory.GetDirectories();

                    String dirCount = subDirs.Length.ToString();
 

                    // Create Key

                    String key = dirName + ";" + dirCount;

                    
 

                    // Security Object

                    DirectorySecurity ds = directory.GetAccessControl(AccessControlSections.Access);

                    

                    // Showing access rules data

                    AuthorizationRuleCollection arc = ds.GetAccessRules(true, true, typeof(NTAccount));

                    

                    // Create List

                    List<ACL> aclList = new List<ACL>();
 

                    foreach (FileSystemAccessRule ar in arc)

                    {
 

                        // Create Object

                        ACL acl = new ACL();
 

                        // Set Values

                        acl.AccountName         = ar.IdentityReference.Value.ToString();

                        acl.Typ                 = ar.AccessControlType.ToString();

                        acl.Rights              = ar.FileSystemRights.ToString();

                        acl.Inherited           = ar.IsInherited.ToString();

                        acl.InheritanceFlags    = ar.InheritanceFlags.ToString();

                        acl.PropagationFlags    = ar.PropagationFlags.ToString();
 

                        // Add to List

                        aclList.Add(acl);
 

                    }
 

                    // Add to Dictionary

                    if (! lAclSet.ContainsKey(key))

                    {

                        lAclSet.Add(key, aclList);

                    }
 

                }
 
 

                // Search in Subfolders if recursive true

                if (recursive)

                {

                    foreach (DirectoryInfo subDirectory in directory.GetDirectories())

                    {

                        readDir(subDirectory, excludePath, lAclSet, recursive);

                    }

                }

            }

            catch

            {

                return;

            }
 

        }
 
 

        public String DirectoryName

        {

            get { return mDirectoryName; }

            set { mDirectoryName = value; }

        }
 

        public String AccountName

        {

            get { return mAccountName; }

            set { mAccountName = value; }

        }
 

        public String Typ

        {

            get { return mTyp; }

            set { mTyp = value; }

        }
 

        public String Rights

        {

            get { return mRights; }

            set { mRights = value; }

        }
 

        public String Inherited

        {

            get { return mInherited; }

            set { mInherited = value; }

        }
 

        public String InheritanceFlags

        {

            get { return mInheritanceFlags; }

            set { mInheritanceFlags = value; }

        }
 

        public String PropagationFlags

        {

            get { return mPropagationFlags; }

            set { mPropagationFlags = value; }

        }
 

        public int DirectoryCount

        {

            get { return mDirectoryCount; }

            set { mDirectoryCount = value; }

        }

    }

}

Open in new window

0
Comment
Question by:schubduese
  • 2
  • 2
  • 2
6 Comments
 
LVL 5

Expert Comment

by:rendaduiyan
ID: 24352354
It seems you need a parameter for current depth.
Or you can count from your structure.
0
 

Author Comment

by:schubduese
ID: 24352366
Yes, the parameter for depth is known... the question is how can I handle the depth!
0
 
LVL 5

Expert Comment

by:rendaduiyan
ID: 24352377
you can use it to decide whether or not going down.
if (recursive && no more than the MaxDepth)
{
      ///.....
}
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 6

Expert Comment

by:alex_paven
ID: 24352446
To clarify (pardon the terrible pseudo-code):

method([your arguments], int depth)

{

  if (depth > maxDepth) return;

  

  [your code...]

  

  foreach (directory in directories)

  {

    method([your arguments], depth + 1);

  }

}

Open in new window

0
 

Author Comment

by:schubduese
ID: 24352606
Probably my Question was not really clear, sorry for that, I'll start another try

The goal with maxdepth is, that the user can give a parameter with the depth, because he's probably not interested in the 3th, 4th etc. level.

So for an Director C:\Windows and a maxlevel of 1 he will scan every subdirectory directly under C:\Windows. With a maxlevel of 2, the scan will go one level deeper (e.g. C:\Windows\Folder1\Subfolder1)

Hope it's more understandable. Sorry for the circumstances...
0
 
LVL 6

Accepted Solution

by:
alex_paven earned 500 total points
ID: 24352626
Ok, I'll clarify the pseudocode a bit more, seems I was too terse (note the currentDepth + 1 !!!):
private static void readDir(DirectoryInfo directory, List<Object> excludePath, Dictionary<String,List<ACL>> lAclSet, bool recursive, int maxDepth, int currentDepth)

{

  if (currentDepth >= maxDepth) return;
 

  //[do stuff....]
 

  if (recursive)

  {

    foreach (DirectoryInfo subDirectory in directory.GetDirectories())

    {

      readDir(subDirectory, excludePath, lAclSet, recursive, maxDepth, currentDepth + 1);

    }

  }

}

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Host asp.net pages 5 25
Exit the loop 4 35
Code works but it's slow 24 42
Crystal reports vb.net 2 7
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now