写入列表<字符串>的目录与子目录

本文关键字:子目录 列表 字符串 | 更新日期: 2023-09-27 17:56:12

现在,我知道 Stackoverflow 上已经有很多关于文件夹递归和获取包含其子目录等文件夹的问题。 pp.,但我还没有找到任何与我在这里遇到的内容相关的内容。

我的问题如下:

从这里(页面底部)获取了有关文件夹递归的代码片段,并根据我的需求对其进行了调整;也就是说,让它不将所有(子)目录写入控制台,而是让它将它们添加到列表中。这是我的代码(请注意注释掉的部分):

private static List<String> ShowAllFoldersUnder(string path)
{
   var folderList = new List<String>();
   try
   {
      if ((File.GetAttributes(path) & FileAttributes.ReparsePoint)
         != FileAttributes.ReparsePoint)
      {
         foreach (string folder in Directory.GetDirectories(path))
         {
            folderList.Add(folder);
            // Console.WriteLine(folder);
            ShowAllFoldersUnder(folder);
         }
      }
   }
   catch (UnauthorizedAccessException) { }
   return folderList;
}

这就是我所说的(Dir是包含路径的string):

var _folders = ShowAllFoldersUnder(Dir);
foreach (string folder in _folders)
{
    Console.WriteLine(folder);
}

问题只是将第一级文件夹添加到列表中,这意味着我的输出是例如:

[...]
C:'Users'Test'Pictures
C:'Users'Test'Recent
C:'Users'Test'Saved Games
C:'Users'Test'Searches
C:'Users'Test'SendTo
[...]

但是,如果我取消Console.WriteLine(folder);从该方法中注释,它会将所有(子)目录回显到控制台:

[...]
C:'Users'Test'AppData'Roaming'Microsoft'Internet Explorer'Quick Launch'User Pinned
C:'Users'Test'AppData'Roaming'Microsoft'Internet Explorer'Quick Launch'User Pinned'ImplicitAppShortcuts
C:'Users'Test'AppData'Roaming'Microsoft'Internet Explorer'Quick Launch'User Pinned'TaskBar
C:'Users'Test'AppData'Roaming'Microsoft'Internet Explorer'UserData
C:'Users'Test'AppData'Roaming'Microsoft'Internet Explorer'UserData'Low
C:'Users'Test'AppData'Roaming'Microsoft'MMC
C:'Users'Test'AppData'Roaming'Microsoft'Network
[...]

在花了几个小时研究可能是我的错误之后,我很绝望。有人知道是什么导致了我的问题吗?

写入列表<字符串>的目录与子目录

您似乎对递归调用中找到的文件夹没有执行任何操作 ShowAllFoldersUnder .

此修改应该可以解决它。改变:

ShowAllFoldersUnder(folder);

自:

folderList.AddRange(ShowAllFoldersUnder(folder));

在生产代码中,我可能会重构它以在整个递归过程中使用单个List,以避免创建和合并多个列表的任何开销。

将方法修改为此

private static void ShowAllFoldersUnder(string path, List<string> folderList)
{
   try
   {
      if ((File.GetAttributes(path) & FileAttributes.ReparsePoint)
         != FileAttributes.ReparsePoint)
      {
         foreach (string folder in Directory.GetDirectories(path))
         {
            folderList.Add(folder);
            // Console.WriteLine(folder);
            ShowAllFoldersUnder(folder, folderList);
         }
      }
   }
   catch (UnauthorizedAccessException) { }
}

现在这样称呼它

var _folders = new List<string>();
ShowAllFoldersUnder(Dir, _folders);

这样,您可以防止其他答案中的许多列表创建和内存消耗。 通过使用这种方式,您可以向该方法提供一个初始列表,它将向该方法添加所有条目,但其他答案每次都会生成一个列表,然后将结果复制到上面的列表,这将导致大量的内存分配, 复制和解除分配。

该方法

ShowAllFoldersUnder返回字符串列表,但您实际使用它的唯一时间是在"main"方法中,您将它们写入Console

你需要改变

ShowAllFoldersUnder(folder);

folderList.AddRange(ShowAllFoldersUnder(folder));