An in depth understanding of traversing the file system directory tree

  • 2020-05-12 03:09:05
  • OfStack

In c# you can traverse all files on a specified drive or in a nested directory under a specified directory or at any depth. You can retrieve directory names and file names in the string form by traversing, as well as other information in the System.IO.FileInfo or System.IO.DirectoryInfo object form. Directory traversal can be achieved by recursive traversal and stack traversal.
The recursive traversal
The recursive algorithm is simple, but the nested tree is too deep and may cause stack overflow exceptions.

/// <summary>
    ///  Access the directory tree recursively 
    /// </summary>
    class RecursiveAccessDirectory
    {
        // Declare and instantiate 1 Sets of strings 
        static System.Collections.Specialized.StringCollection log
            = new System.Collections.Specialized.StringCollection();
        static void Main()
        {
            /* The department code loops through files on all of the native drives 
             * 
             * 
            // Returns an array of strings of computer logical drive names 
            // Includes an optical drive and a mobile drive that connects the computer 
            string[] drives = System.Environment.GetLogicalDrives();
            foreach (string dr in drives)
            {
                System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
                if (!di.IsReady)
                {
                    Console.WriteLine(" drive  {0}  Can't read ", di.Name);
                    continue;
                }
                System.IO.DirectoryInfo rootDir = di.RootDirectory;
                WalkDirectoryTree(rootDir);
            }
           */
            /* Loops through folders in the specified directory 
             * 
             */
            System.IO.DirectoryInfo rootDir = new System.IO.DirectoryInfo(@"C:\test");
            WalkDirectoryTree(rootDir);
            Console.WriteLine(" Restrict user access to files :");
            foreach (string s in log)
            {
                Console.WriteLine(s);
            }
            Console.Read();
        }

       
        static void WalkDirectoryTree(System.IO.DirectoryInfo root)
        {
            System.IO.FileInfo[] files = null;
            System.IO.DirectoryInfo[] subDirs = null;
            try
            {
                //GetFiles The argument to a method can contain wildcards. 
                // Even if there are no matching files in the directory, the return length is 0 An array object that is not empty, 
                // So the recursive function can be placed if (files != null) In the water. 
                // The following is a search for all files with suffixed names. 
                files = root.GetFiles("*.*");
            }
            // The request permission exceeds the application provided permission to throw an exception 
            catch (System.UnauthorizedAccessException e)
            {
                // When access to a folder is denied, 
                // You can raise your rights and then access it again. 
                log.Add(e.Message);
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
            }

            if (files != null)
            {
                foreach (System.IO.FileInfo fi in files)
                {
                    Console.WriteLine("{0}: {1} {2}", fi.FullName, fi.Length, fi.CreationTime);
                }
                subDirs = root.GetDirectories();
                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    WalkDirectoryTree(dirInfo);
                }
            }
        }
    }

Stack traversal
Take advantage of the generic Stack < T > Collection type implementation, which is a last in, first out (LIFO) stack.

/// <summary>
    ///  Access the directory tree by stack 
    /// </summary>
    class StackAccessDirectory
    {

        static void Main()
        {
            TraverseTree(@"C:\test");
            Console.Read();
        }

        public static void TraverseTree(string root)
        {
            Stack<string> dirs = new Stack<string>(20);
            if (!System.IO.Directory.Exists(root))
            {
                throw new ArgumentException();
            }
            dirs.Push(root);
            while (dirs.Count > 0)
            {
                string currDir = dirs.Pop();
                string[] subDirs;
                try
                {
                    subDirs = System.IO.Directory.GetDirectories(currDir);
                }
                catch (System.UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                string[] files=null;
                try
                {
                    files=System.IO.Directory.GetFiles(currDir);
                }
                catch(System.UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch(System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                foreach (string file in files)
                {
                    try
                    {
                        System.IO.FileInfo fi = new System.IO.FileInfo(file);
                        Console.WriteLine("{0}: {1} {2}", fi.Name, fi.Length, fi.CreationTime);
                    }
                    catch (System.IO.FileNotFoundException e)
                    {
                        Console.WriteLine(e.Message);
                        continue;
                    }
                }
                foreach (string str in subDirs)
                    dirs.Push(str);
            }
        }
    }


Related articles: