2012-05-19 88 views
8

我有一些代碼:僅在C#中列出子文件夾?

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文件。我只需要列出子文件夾....我不知道該怎麼做?謝謝!

回答

16

你可以試試這個:

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

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

我該如何填充我的listbox2這些子文件夾? –

+1

完美! Tahanks! –

1

如果您希望獲得...目錄,請使用EnumerateDirectoriesGetDirectories而不是GetFiles

+0

那麼,我該怎麼把()的裏面? :FileInfo [] Files = dinfo.GetDirectories(); –

+0

@EliteGamer - 您是否閱讀過鏈接?你真的需要學習閱讀文檔。列出返回類型和所需參數(如果有)。 – Oded

+0

對不起,我甚至不知道那些鏈接... –

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); 
} 
+0

太棒了!感謝你的回答!! –

+1

不客氣。 –

相關問題