列出目录+子目录中的所有文件和目录

我想列出目录中包含的每个文件和目录以及该目录的子目录。 如果我selectC:\作为目录,那么程序将获取它所访问的硬盘驱动器上的每个文件和文件夹的名称。

列表可能看起来像

 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 \一个
 FD \ B \ b
 FD \ A \ A \的1.txt
 FD \ A \ A \ A \
 FD \ A \ B \的1.txt
 FD \ A \ B \一个
 FD \ B \一个\的1.txt
 FD \ B \一个\一个\
 FD \ B \ b \的1.txt
 FD \ B \ b \一
string[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories); 

其中*.*是匹配文件的模式

如果号码簿也需要你可以这样做:

  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(); } 

Directory.GetFileSystemEntries存在于.NET 4.0+中,并返回文件和目录。 像这样调用它:

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

请注意,它不会处理尝试列出您无权访问的子目录(UnauthorizedAccessException)的内容,但它可能足以满足您的需要。

使用GetDirectoriesGetFiles方法来获取文件夹和文件。

使用SearchOption AllDirectories可以获取子文件夹中的文件夹和文件。

恐怕, GetFiles方法返回文件列表而不是目录。 问题中的列表提示我结果应该包括文件夹。 如果你想要更多的自定义列表,你可以尝试recursion调用GetFilesGetDirectories 。 尝试这个:

 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); } 

提示:如果您需要检查任何特定属性,则可以使用FileInfoDirectoryInfo类。

 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); } } 

如果您无法访问目录树内的子文件夹,则Directory.GetFiles会停止并引发exception,从而在接收string[]中生成空值。

在这里,看到这个答案https://stackoverflow.com/a/38959208/6310707

它pipe理循环内的exception,并继续工作,直到整个文件夹被遍历。

逻辑和有序的方式:

 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); } } } } } 

以下示例处理exception的目录树中最快 (非并行)的方式列表文件和子文件夹。 使用Directory.EnumerateDirectories使用SearchOption.AllDirectories来枚举所有目录会更快,但如果遇到UnauthorizedAccessException或PathTooLongException,则此方法将失败。

使用通用堆栈集合types,这是后进先出(LIFO)堆栈,不使用recursion。 从https://msdn.microsoft.com/en-us/library/bb513869.aspx ,允许您枚举所有子目录和文件,并有效地处理这些例外。

  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); } } } 
 using System.IO; using System.Text; string[] filePaths = Directory.GetFiles(@"path", "*.*", SearchOption.AllDirectories); 
Interesting Posts