列出并分离c#中的指挥

时间:2014-09-17 14:54:24

标签: c# list directory

使用 Directory.GetDirectories 我可以列出所有文件夹,但我需要将子文件夹与确定点分开,例如,我有这个列表

  • folderA /
  • FolderB中/
  • folderA / subFolderA /
  • FolderB中/ subFolderB /
  • folderA / subFolderA / SubFolderB
  • FolderB中/ subFolderB / SubFolderB

但我需要将每个路径,folderA分别与folderB

分开
  • folderA /
  • folderA / subFolderA /
  • folderA / subFolderA / SubFolderB

和   - folderB /   - folderB / subFolderB /   - folderB / subFolderB / SubFolderB

可能吗?

2 个答案:

答案 0 :(得分:0)

您可以使用“搜索”选项为您提供顶级目录,然后依次处理每个目录以获取其子目录

Directory.GetDirectories(thePath, aSearchPattern ,SearchOption.TopDirectoryOnly);

答案 1 :(得分:0)

我会尝试将EnumerateDirectories返回的目录分成两个列表,具体取决于字符串的开头方式

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方法的不同之处如下:   当您使用EnumerateDirectories时,您可以开始枚举   返回整个集合之前的名称集合;当你   使用GetDirectories,您必须等待整个名称数组   在您可以访问该数组之前返回。因此,当你是   使用许多文件和目录,EnumerateDirectories可以   效率更高。