SoFunction
Updated on 2025-03-07

In-depth understanding of traversing file system directory trees


/// <summary>
/// Access the directory tree through recursive mode
    /// </summary>
    class RecursiveAccessDirectory
    {
//Declare and instantiate a string collection
        static log
            = new ();
        static void Main()
        {
/*The department code loops through files on all drives of this machine
             *
             *
//Return the string array of computer logical drive names
//Including optical drives and mobile drives connected to computers
            string[] drives = ();
            foreach (string dr in drives)
            {
                di = new (dr);
                if (!)
                {
("Drive {0} cannot be read out", );
                    continue;
                }
                rootDir = ;
                WalkDirectoryTree(rootDir);
            }
           */
/*Drive access to folders in the specified directory
             *
             */
            rootDir = new (@"C:\test");
            WalkDirectoryTree(rootDir);
("Restrict user access to files:");
            foreach (string s in log)
            {
                (s);
            }
            ();
        }

      
        static void WalkDirectoryTree( root)
        {
            [] files = null;
            [] subDirs = null;
            try
            {
//The parameters of the GetFiles method can contain wildcards.
//Even if there is no matching file in the directory, return an array object with length 0 and not empty.
//So recursive functions can be placed in if (files != null).
//The following is to find all files with suffix names.
                files = ("*.*");
            }
//The request permission exceeds the application's permission to throw an exception
            catch ( e)
            {
//When access to a folder is denied,
//You can increase your permissions and access it again.
                ();
            }
            catch ( e)
            {
                ();
            }

            if (files != null)
            {
                foreach ( fi in files)
                {
                    ("{0}: {1} {2}", , , );
                }
                subDirs = ();
                foreach ( dirInfo in subDirs)
                {
                    WalkDirectoryTree(dirInfo);
                }
            }
        }
    }