在C#中仅列出子文件夹?

时间:2012-05-19 20:04:09

标签: c# directory visual-c#-express-2010

我有一些代码:

string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, @"documents\iracing\setups\");
DirectoryInfo dinfo = new DirectoryInfo(pathDownload); // Populates field with all Sub Folders
FileInfo[] Files = dinfo.GetFiles("*.sto");
foreach (FileInfo file in Files)
{
     listBox2.Items.Add(file.Name);
}

我希望显示:documents\iracing\setups\的子文件夹,而不是文件...包括.sto文件。我只需要列出子文件夹....我不知道该怎么做?谢谢!

3 个答案:

答案 0 :(得分:17)

你可以试试这个:

DirectoryInfo directory = new DirectoryInfo(pathDownload);
DirectoryInfo[] directories = directory.GetDirectories();

foreach(DirectoryInfo folder in directories)
     listBox2.Items.Add(folder.Name);

答案 1 :(得分:2)

只需使用此功能

string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, @"documents\iracing\setups\");
DirectoryInfo dinfo = new DirectoryInfo(pathUser); // Populates field with all Sub Folders
DirectoryInfo[] directorys = dinfo.GetDirectories();
foreach (DirectoryInfo directory in directorys)
{
    listBox2.Items.Add(directory.Name);
}

答案 2 :(得分:1)

如果您希望获取...目录,请使用EnumerateDirectoriesGetDirectories代替GetFiles