C#如何获取当前文件夹路径的所有子文件夹?例如,我有一个公共文件夹,它是父文件夹。所以在公共文件夹中我有图像文件夹,在图像文件夹中我有AA,BB,CC,...文件夹。
可以在这里递归吗?
P / S:我想得到树视图的结果:
Public
--Images
----AA
----BB
----CC
答案 0 :(得分:2)
据我了解,您希望列出仅包含文件的给定路径下的子目录。
static IEnumerable<string> GetSubdirectoriesContainingOnlyFiles(string path)
{
return from subdirectory in Directory.GetDirectories(path, "*", SearchOption.AllDirectories)
where Directory.GetDirectories(subdirectory).Length == 0
select subdirectory;
}
或者你也可以使用它。
DirectoryInfo dInfo = new DirectoryInfo(<path to dir>);
DirectoryInfo[] subdirs = dInfo.GetDirectories();
答案 1 :(得分:1)
使用Microsoft的Ix-Main包:
static IEnumerable<string> EnumerateSubdirs(string path)
{
return EnumerableEx.Expand(
Directory.EnumerateDirectories(path),
subPath => Directory.EnumerateDirectories(subPath));
}
Expand
会递归地将方法应用于集合,并以广度优先的方式返回每个项目。所以,如果你在那里传递“公共”,它会给你:
Public\Images
Public\Images\AA
Public\Images\BB
Public\Images\CC
如果您想要包含顶级文件夹,那也很容易:
static IEnumerable<string> EnumerateSubdirs(string path)
{
var subDirs = EnumerableEx.Expand(
Directory.EnumerateDirectories(path),
subPath => Directory.EnumerateDirectories(subPath));
return EnumerableEx.Return(path).Concat(subDirs);
}
哪会导致:
Public
Public\Images
Public\Images\AA
Public\Images\BB
Public\Images\CC
答案 2 :(得分:0)
试试这个:
String[] dirs= System.IO.Directory.GetDirectories("C:\\");
foreach(string str in dirs)
Console.WriteLine(str);
答案 3 :(得分:0)
试试这个
Dictionary<string, string> dicData = new Dictionary<string, string>();
private void processDirectory(string startLocation)
{
foreach (var directory in Directory.GetDirectories(startLocation))
{
DirectoryInfo dr = new DirectoryInfo(directory);
{
if (!dicData.ContainsKey(dr.Parent.Name))
dicData.Add(dr.Parent.Name, dr.Name);
else
dicData[dr.Parent.Name] += "," + dr.Name;
}
processDirectory(directory);
}
}
A --> B , C
B --> X --> Y -->Z
C --> P --> Q