如何列出目录中的所有子目录

我正在处理一个项目,我需要列出目录中的所有子目录,例如我如何列出所有的子目录在c:\

使用Directory.GetDirectories获取由“your_directory_path”指定的目录的子目录。 结果是一个string数组。

 var directories = Directory.GetDirectories("your_directory_path"); 

默认情况下,只返回一级深度的子​​目录。 有一些选项可以recursion地返回所有的结果,并logging在这里 ,并显示在Clive的答案中。


避免UnauthorizedAccessException

如果你打到一个你没有访问权限的目录,很容易就会得到一个UnauthorizedAccessException

您可能必须创build自己的处理exception的方法,如下所示:

 public class CustomSearcher { public static List<string> GetDirectories(string path, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly) { if (searchOption == SearchOption.TopDirectoryOnly) return Directory.GetDirectories(path, searchPattern).ToList(); var directories = new List<string>(GetDirectories(path, searchPattern)); for (var i = 0; i < directories.Count; i++) directories.AddRange(GetDirectories(directories[i], searchPattern)); return directories; } private static List<string> GetDirectories(string path, string searchPattern) { try { return Directory.GetDirectories(path, searchPattern).ToList(); } catch (UnauthorizedAccessException) { return new List<string>(); } } } 

然后像这样调用它:

 var directories = CustomSearcher.GetDirectories("your_directory_path"); 

容易如此:

 string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories); 
 FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult result = fbd.ShowDialog(); string[] files = Directory.GetFiles(fbd.SelectedPath); string[] dirs = Directory.GetDirectories(fbd.SelectedPath); foreach (string item2 in dirs) { FileInfo f = new FileInfo(item2); listBox1.Items.Add(f.Name); } foreach (string item in files) { FileInfo f = new FileInfo(item); listBox1.Items.Add(f.Name); } 
 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TRIAL { public class Class1 { static void Main(string[] args) { string[] fileArray = Directory.GetDirectories("YOUR PATH"); for (int i = 0; i < fileArray.Length; i++) { Console.WriteLine(fileArray[i]); } Console.ReadLine(); } } }