If you don't want to create DirectoryInfo
or FileInfo
classes which can sometimes cause errors and introduce additional overhead, you could do it this way instead:
void DirSearch(string sDir)
{
foreach (var d in System.IO.Directory.GetDirectories(sDir))
{
ListBox1.Items.Add(d.TrimEnd(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar).Last());
DirSearch(d);
}
}
It's also a hair bit faster, depending on how many and how large the directories you're searching are...
If you don't need it to be cross-platform/can always guarantee the file system has a slash separator, you can make it a little "shorter"/less verbose.
void DirSearch(string sDir)
{
foreach (var d in System.IO.Directory.GetDirectories(sDir))
{
ListBox1.Items.Add(d.TrimEnd('\\').Split('\\').Last());
DirSearch(d);
}
}