【发布时间】:2015-08-29 23:21:22
【问题描述】:
现在,我知道 Stackoverflow 上已经有很多关于文件夹递归和获取文件夹(包括它的子目录等)的问题,但我没有找到与我在这里遇到的任何相关的任何问题。
我的问题如下:
我从here(页面底部)获取了关于文件夹递归的代码 sn-p 并根据我的需要进行了调整;也就是说,让它不将所有(子)目录写入控制台,而是让它将它们添加到列表中。这是我的代码(注意被注释掉的部分):
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
[...]
在花了数小时研究可能是我的错误之后,我感到绝望。有人知道是什么导致了我的问题吗?
【问题讨论】:
标签: c# .net list recursion directory