在c#中列出并分隔目录
本文关键字:分隔 | 更新日期: 2023-09-27 18:22:09
使用Directory.GetDirectories我可以列出所有文件夹,但我需要将子文件夹从一个确定的点分开,例如,我有这个列表
- 文件夹A/
- 文件夹B/
- 文件夹A/subFolderA/
- 文件夹B/subFolderB/
- 文件夹A/subFolderA/SubFolderB
- 文件夹B/subFolderB/subFolderB
但我需要将每个路径,文件夹A到文件夹B 分开
- 文件夹A/
- 文件夹A/subFolderA/
- 文件夹A/subFolderA/SubFolderB
而且-文件夹B/-文件夹B/subFolderB/-文件夹B/subFolderB/subFolderB
有可能吗?
您可以使用搜索选项为您提供顶级目录,然后依次处理每个目录以获得其子目录
Directory.GetDirectories(thePath, aSearchPattern ,SearchOption.TopDirectoryOnly);
根据字符串以开头的方式,我会尝试将EnumerateDirectory返回的目录分为两个列表
List<String> foldersA = new List<string>();
List<String> foldersB = new List<string>();
List<String> otherFolders = new List<string>(); // Eventually
string rootPath = @"D:'temp";
foreach(string s in Directory.EnumerateDirectories(rootPath, "*", SearchOption.AllDirectories))
{
// remove the rootPath part to apply the StartsWith check
string temp = s.Substring(rootPath.Length + 1);
if(s.StartsWith("folderA"))
foldersA.Add(temp);
else if(s.StartsWith("folderB"))
foldersB.Add(temp);
else
otherFolders.Add(temp);
}
来自MSDN
EnumerateDirectories和GetDirectories方法的区别如下:使用EnumerateDirectory时,可以开始枚举返回整个集合之前的名称集合;当你使用GetDirectories,必须等待整个名称数组在访问数组之前返回。因此,当你使用许多文件和目录时,EnumerateDirectory可以更高效。