如何列出忽略文件的所有可能的目录和子文件夹的路径

本文关键字:路径 文件夹 何列出 文件 有可能 | 更新日期: 2023-09-27 18:18:34

我希望从根目录获得所有可能的文件夹路径,忽略所有仅以文件结尾的路径。getDirectory没有列出每个可能的路径。

例如:根:文件夹 A 和 B

      path a - c
      path a - c - d
      path a - c - x
      path b - e
      path b - e - f
      path b - e - g

如何列出忽略文件的所有可能的目录和子文件夹的路径

您需要递归迭代并访问每个文件夹。请参阅此 MSDN 文章中的示例。

Directory.GetDirectory(( 返回所有直系子项。

您需要使调用递归。 下面的伪代码 - 我目前无法访问计算机。

// Output All Leaf Nodes From Root
EnumerateDirectory(@"c:'");
public void EnumerateDirectory(string baseDirectory)
{
    if( Directory.GetDirectories(baseDirectory).Count == 0 )
    {
         // This is an end, leaf node.
         Output("This is a leaf node.");
         return;
    }
    foreach(var directory in Directory.GetDirectories(baseDirectory) )
    {
          EnumerateDirectory(directory);
          return;
    }
}

没有理由编写递归函数。您可以只使用其中一个重载。

oRoot.GetDirectories("*", SearchOption.AllDirectories);

这种方法解决了Strillo在对Nick的回答的评论中提到的问题。它也更有效率。

DirectoryInfo info = new DirectoryInfo(yourRoot);
foreach (var d in info.EnumerateDirectories("*",SearchOption.AllDirectories))
{
    Console.WriteLine(d.FullName);
}

阅读此 MSDN 文档的"备注"部分。

如果你有很多目录要查看,并且需要跳过用户无权访问的目录,最好的选择是枚举目录:

        // LINQ query.
        var dirs = from dir in 
                 Directory.EnumerateDirectories("C:'", "*",                         SearchOption.AllDirectories)
                   select dir;
        // Show results.
        foreach (var dir in dirs)
        {
            // Do something with the dir
        }
private void ListAllDirectories(string root)
{
    DirectoryInfo dr = new DirectoryInfo(root);
                Console.WriteLine(dr.FullName);
                var directories = dr.GetDirectories();
                foreach (var directory in directories)
                {
                    try
                    {
                        ListAllDirectories(directory.FullName);
                    }
                    catch
                    {
                        continue;
                    }
                }
}

Catch 用于处理未经授权的异常等,只是为了让您入门。

这将处理DirectoryNotFoundExceptionUnauthorizedAccessException

IEnumerable<string> GetFoldersRecursive(string directory)
{
    var result = new List<string>();
    var stack = new Stack<string>();
    stack.Push(directory);
    while (stack.Count > 0)
    {
        var dir = stack.Pop();
        try
        {
            result.AddRange(Directory.GetDirectories(dir, "*.*"));
            foreach (string dn in Directory.GetDirectories(dir))
            {
                stack.Push(dn);
            }
        }
        catch
        {
        }
    }
    return result;
}

请注意,由于try/catch块,这可能不如其他方法的性能。

*免责声明:我最初没有写这段代码(在SO上找到它!(,我只是修改了它以适应需要。

最后将

我的 VB.NET 版本转换为 C#:

namespace ExtensionMethods
{
    public static class DirectoryExtensions
    {
        public static List<DirectoryInfo> GetSubFolders(this DirectoryInfo rootFolder)
        {
            if (rootFolder == null)
            {
                throw new ArgumentException("Root-Folder must not be null!", "rootFolder");
            }
            List<DirectoryInfo> subFolders = new List<DirectoryInfo>();
            AddSubFoldersRecursively(rootFolder, ref subFolders);
            return subFolders;
        }
        private static void AddSubFoldersRecursively(DirectoryInfo rootFolder, ref List<DirectoryInfo> allFolders)
        {
            try
            {
                allFolders.Add(rootFolder);
                foreach (DirectoryInfo subFolder in rootFolder.GetDirectories())
                {
                    AddSubFoldersRecursively(subFolder, ref allFolders);
                }
            }
            catch (UnauthorizedAccessException exUnauthorized)
            {
                // go on 
            }
            catch (DirectoryNotFoundException exNotFound)
            {
                // go on 
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}

如果有人对 VB.NET 版本感兴趣:

Public Module DirectoryExtensions
    <Runtime.CompilerServices.Extension()>
    Public Function GetSubFolders(ByVal rootFolder As DirectoryInfo) As List(Of DirectoryInfo)
        If rootFolder Is Nothing Then
            Throw New ArgumentException("Root-Folder must not be null!", "rootFolder")
        End If
        Dim subFolders As New List(Of DirectoryInfo)
        AddSubFoldersRecursively(rootFolder, subFolders)
        Return subFolders
    End Function
    Private Sub AddSubFoldersRecursively(rootFolder As DirectoryInfo, ByRef allFolders As List(Of DirectoryInfo))
        Try
            allFolders.Add(rootFolder)
            For Each subFolder In rootFolder.GetDirectories
                AddSubFoldersRecursively(subFolder, allFolders)
            Next
       Catch exUnauthorized As UnauthorizedAccessException
           ' go on '
       Catch exNotFound As DirectoryNotFoundException
           ' go on '
       Catch ex As Exception
           Throw
       End Try
    End Sub
End Module

测试:

Dim result = Me.FolderBrowserDialog1.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
     Dim rootPath = Me.FolderBrowserDialog1.SelectedPath
     Dim rootFolder = New DirectoryInfo(rootPath)
     Dim query = From folder In rootFolder.GetSubFolders()
            Select folder.FullName
     If query.Any Then
          Me.ListBox1.Items.AddRange(query.ToArray)
     End If
 End If