List all files and directories in a directory + subdirectories

前端 未结 15 1874
陌清茗
陌清茗 2020-12-13 01:46

I want to list every file and directory contained in a directory and subdirectories of that directory. If I chose C:\\ as the directory, the program would get every name of

相关标签:
15条回答
  • 2020-12-13 02:12

    The following example the fastest (not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.

    Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.

        public class StackBasedIteration
    {
        static void Main(string[] args)
        {
            // Specify the starting folder on the command line, or in 
            // Visual Studio in the Project > Properties > Debug pane.
            TraverseTree(args[0]);
    
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
    
        public static void TraverseTree(string root)
        {
            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack<string> dirs = new Stack<string>(20);
    
            if (!System.IO.Directory.Exists(root))
            {
                throw new ArgumentException();
            }
            dirs.Push(root);
    
            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                {
                    subDirs = System.IO.Directory.EnumerateDirectories(currentDir); //TopDirectoryOnly
                }
                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable 
                // to ignore the exception and continue enumerating the remaining files and 
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The 
                // choice of which exceptions to catch depends entirely on the specific task 
                // you are intending to perform and also on how much you know with certainty 
                // about the systems on which this code will run.
                catch (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.EnumerateFiles(currentDir);
                }
    
                catch (UnauthorizedAccessException e)
                {
    
                    Console.WriteLine(e.Message);
                    continue;
                }
    
                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (string file in files)
                {
                    try
                    {
                        // Perform whatever action is required in your scenario.
                        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)
                    {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    catch (UnauthorizedAccessException e)
                    {                    
                        Console.WriteLine(e.Message);
                        continue;
                    }
                }
    
                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                    dirs.Push(str);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 02:14

    If you don't have access to a subfolder inside the directory tree, Directory.GetFiles stops and throws the exception resulting in a null value in the receiving string[].

    Here, see this answer https://stackoverflow.com/a/38959208/6310707

    It manages the exception inside the loop and keep on working untill the entire folder is traversed.

    0 讨论(0)
  • 2020-12-13 02:15

    Create List Of String

        public static List<string> HTMLFiles = new List<string>();
    
     private void Form1_Load(object sender, EventArgs e)
            {
    
         HTMLFiles.AddRange(Directory.GetFiles(@"C:\DataBase", "*.txt"));
                foreach (var item in HTMLFiles)
                {
                    MessageBox.Show(item);
                }
    
    }
    
    0 讨论(0)
  • 2020-12-13 02:19
    public static void DirectorySearch(string dir)
    {
        try
        {
            foreach (string f in Directory.GetFiles(dir))
            {
                Console.WriteLine(Path.GetFileName(f));
            }
            foreach (string d in Directory.GetDirectories(dir))
            {
                Console.WriteLine(Path.GetFileName(d));
                DirectorySearch(d);
            }
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    

    Note: the function shows only names without relative paths.

    0 讨论(0)
  • 2020-12-13 02:21

    Use the GetDirectories and GetFiles methods to get the folders and files.

    Use the SearchOption AllDirectories to get the folders and files in the subfolders also.

    0 讨论(0)
  • 2020-12-13 02:21

    the logical and ordered way:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    
    namespace DirLister
    {
    class Program
    {
        public static void Main(string[] args)
        {
            //with reflection I get the directory from where this program is running, thus listing all files from there and all subdirectories
            string[] st = FindFileDir(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
            using ( StreamWriter sw = new StreamWriter("listing.txt", false ) )
            {
                foreach(string s in st)
                {
                    //I write what I found in a text file
                    sw.WriteLine(s);
                }
            }
        }
    
        private static string[] FindFileDir(string beginpath)
        {
            List<string> findlist = new List<string>();
    
            /* I begin a recursion, following the order:
             * - Insert all the files in the current directory with the recursion
             * - Insert all subdirectories in the list and rebegin the recursion from there until the end
             */
            RecurseFind( beginpath, findlist );
    
            return findlist.ToArray();
        }
    
        private static void RecurseFind( string path, List<string> list )
        {
            string[] fl = Directory.GetFiles(path);
            string[] dl = Directory.GetDirectories(path);
            if ( fl.Length>0 || dl.Length>0 )
            {
                //I begin with the files, and store all of them in the list
                foreach(string s in fl)
                    list.Add(s);
                //I then add the directory and recurse that directory, the process will repeat until there are no more files and directories to recurse
                foreach(string s in dl)
                {
                    list.Add(s);
                    RecurseFind(s, list);
                }
            }
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题