List of all files and directories in the directory + subdirectories

I want to list each file and directory contained in the directory and subdirectories of this directory. If I chose C: \ as a directory, the program will receive every name of each file and folder on the hard drive to which it had access.

The list may look like

 fd \ 1.txt
 fd \ 2.txt
 fd \ a \
 fd \ b \
 fd \ a \ 1.txt
 fd \ a \ 2.txt
 fd \ a \ a \
 fd \ a \ b \
 fd \ b \ 1.txt
 fd \ b \ 2.txt
 fd \ b \ a
 fd \ b \ b
 fd \ a \ a \ 1.txt
 fd \ a \ a \ a \
 fd \ a \ b \ 1.txt
 fd \ a \ b \ a
 fd \ b \ a \ 1.txt
 fd \ b \ a \ a \
 fd \ b \ b \ 1.txt
 fd \ b \ b \ a
+48
c # directory subdirectories
Sep 08 '12 at 16:24
source share
9 answers
string[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories); 

where *.* is the template for matching files

If a directory is also needed, you can do the following:

  foreach ( var file in allfiles){ FileInfo info = new FileInfo(file); // Do something with the Folder or just add them to a list via nameoflist.add(); } 
+106
Sep 08
source share

Directory.GetFileSystemEntries exists in .NET 4.0+ and returns both files and directories. Call it like this:

 string[] entries = Directory.GetFileSystemEntries( path, "*", SearchOption.AllDirectories); 

Please note that it will not cope with attempts to list the contents of subdirectories to which you do not have access (UnauthorizedAccessException), but this may be enough for your needs.

+15
May 09 '14 at 17:48
source share

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

Use SearchOption AllDirectories to get folders and files in subfolders.

+13
Sep 08
source share

I'm afraid the GetFiles method returns a list of files, but not directories. The list in the question tells me that the folders should be listed as a result. If you want a larger custom list, you can try recursively calling GetFiles and GetDirectories . Try the following:

 List<string> AllFiles = new List<string>(); void ParsePath(string path) { string[] SubDirs = Directory.GetDirectories(path); AllFiles.AddRange(SubDirs); AllFiles.AddRange(Directory.GetFiles(path)); foreach (string subdir in SubDirs) ParsePath(subdir); } 

Tip. You can use the FileInfo and DirectoryInfo classes if you need to check any specific attribute.

+3
Aug 21 '13 at 7:10
source share
 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); } } 
+3
Jun 18 '16 at 12:20
source share

If you do not have access to the subfolder inside the directory tree, Directory.GetFiles stops and throws an exception, resulting in a null value in the receiving line [].

Here, see this answer https://stackoverflow.com>.

It manages the exception inside the loop and continues to work until the whole folder is traversed.

0
Aug 15 '16 at 16:48
source share

In the following example, the fastest (non-parallel) list and subfolder file in the processing tree of the directory tree. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to list all directories, but this method will not succeed if it removes UnauthorizedAccessException or PathTooLongException.

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

  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
Nov 26 '16 at 21:59
source share

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
Jun 11 '17 at 7:43 on
source share
 using System.IO; using System.Text; string[] filePaths = Directory.GetFiles(@"path", "*.*", SearchOption.AllDirectories); 
-one
Feb 10 '15 at 7:52
source share



All Articles