Reputation: 1221
How would you get a list of all sub directories and their sub directories (until there are none left) from a root directory.
My current code uses a FolderBrowserDialog (WPF does not have one so I have to take it from winforms), and from there attempts to transverse directories. So far I can only make it transverse 1 level deep, as in
If the music directory is setup as
\rock\metallica\ride the lightning
\rock\aerosmith\
\rock\something\
and the user chooses \rock\ it would only grab files from aerosmith, something, and metallica, and not the sub directory of metallica, ride the lightning.
private void btnAddTestFile_Click(object sender, RoutedEventArgs e)
{
string[] files;
FolderBrowserDialog dlg = new FolderBrowserDialog();
DialogResult result = dlg.ShowDialog();
if (result.ToString() == "OK")
{
InitializePropertyValues();
files = System.IO.Directory.GetFiles(dlg.SelectedPath, "*.mp3");
foreach (string file in files)
{
lstvTrackList.Items.Add(new TrackList{ ID = lstvTrackList.Items.Count.ToString(), TrackName = Regex.Match(file, @".*\\(.*).mp3").Groups[1].Value, TrackPath = file });
}
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dlg.SelectedPath);
foreach (System.IO.DirectoryInfo d in di.GetDirectories())
{
files = System.IO.Directory.GetFiles(d.FullName, "*.mp3");
foreach (string file in files)
{
lstvTrackList.Items.Add(new TrackList{ ID = lstvTrackList.Items.Count.ToString(), TrackName = Regex.Match(file, @".*\\(.*).mp3").Groups[1].Value, TrackPath = file });
}
}
}
}
Basically what I have attempted to do was first add all the loose files from the root directory, then get a list of directories inside the root directory and add those files.
I think I could figure it out if I knew how to crawl all sub directories starting from a root directory, but I don't quite understand how I would achieve that.
Does anyone have any hints, tips, or sample code that allows you to specify a root directory, then crawl every directory (keeping a string array) until no more sub directories are found, so I can grab files from each directory?
Upvotes: 2
Views: 6100
Reputation: 8902
To get all the sub directories you have to pass the SearchOption as the third argument, Which will return all the sub-directories as well.
Directory.GetFiles("","",SearchOption.AllDirectories);
SearchOption
Upvotes: 2