1

I have bunch of directories at a certain paths in the following possible format:

C:\Program Files\Logic\DDC[ 0 ]

C:\Program Files\Logic\DDC[ 1]

C:\Program Files\Logic\DDC[2    ]

C:\Program Files\Logic\DDC[3]

I'd like to accomplish the following:

1)Enumurate all of numbered DDC directories and store their paths them in a List of String

I.E: List<String> ddcPaths -> should have:
ddcPaths[0] = "DDC[0]";
ddcPaths[1] = "DDC[1]";
ddcPaths[2] = "DDC[2]";

2)Enumurate all files directly under the DDC folder but nothing deeper than that

I.E: If DDC[0] has a.txt, b.txt and obj\c.txt, I should get
List<String> ddc_0 -> should have
ddc_0[0] = "a.txt";
ddc_0[1] = "b.txt";

I hope my explanation was clear enough but if something didn't make sense, please let me know.

4

2 回答 2

1

如果你有这样的数据结构,我建议你应该使用一个字典,目录名作为键,文件名列表作为值。例如:

var ddcPaths = new Dictionary<string, List<string>>();
foreach (var directoryInfo in new DirectoryInfo(@"C:\Program Files\Logic\").GetDirectories())
{
    if (directoryInfo.Name.Contains("DDC["))
    {
         ddcPaths.Add(directoryInfo.Name, new List<string>());
         foreach (var fileInfo in directoryInfo.GetFiles())
         {
             ddcPaths[directoryInfo.Name].Add(fileInfo.FullName);
         }
    }
}

但是您应该注意到,U 不能通过 int 索引获取字典值,只能通过键,在此字典中声明(在我们的例子中是文件夹名称)。但是,如果您不想这样做,您可以执行以下操作:

var ddcPaths = new List<string>();
var filePaths = new List<List<string>>();

foreach (var directoryInfo in new DirectoryInfo(@"C:\Program Files\Logic\").GetDirectories())
{
   if (directoryInfo.Name.Contains("DDC["))
   {
       ddcPaths.Add(directoryInfo.Name);
       var tempList = new List<string>();
       foreach (var fileInfo in directoryInfo.GetFiles())
       {
           tempList.Add(fileInfo.FullName);
       }
       filePaths.Add(tempList);
    }
}

但在这种情况下,U 使用两种不同的数据结构来表示相关数据。我建议使用字典是合乎逻辑的。

于 2012-09-10T07:52:59.477 回答
0

您可以使用DirectoryInfo.

DirectoryInfo dirInfo = new DirectoryInfo("yourFolderPath");
IEnumerable<DirectoryInfo> subDirs = dirInfo.EnumerateDirectories();

List<string> subDirsNames = new List<string>();
foreach (var subDir in subDirs)
 {
   subDirsNames.Add(subDir.Name.Trim());
   IEnumerable<string> files = subDir.EnumerateFiles().Select(i => i.Name);
   //do something with this list....
 }
于 2012-09-10T07:51:46.930 回答