How to get Directories name
Currently you are using Directory.GetDirectories
, It will return a string[]
which will consist of full path for the directories. Instead use DirectoryInfo
class, later you can use the property DirectoryInfo.Name
to get only the name of the directories and not the full path like:
void DirSearch(string sDir)
{
DirectoryInfo dirInfo = new DirectoryInfo(sDir);
foreach (var d in dirInfo.GetDirectories("*", SearchOption.AllDirectories))
{
ListBox1.Items.Add(d.Name);
}
}
It appears that you are trying to recursively search all the sub directories as well, you can use the SearchOption.AllDirectories
in your code to include all the sub directories.
There is a simple one-liner:
Directory.GetDirectories(PathToFolder).Select(d => new DirectoryInfo(d).Name);
This should work:
foreach (var d in System.IO.Directory.GetDirectories(@"C:\"))
{
var dir = new DirectoryInfo(d);
var dirName = dir.Name;
ListBox1.Items.Add(dirName);
}
Also, you could shortcut...
foreach (var d in System.IO.Directory.GetDirectories(@"C:\"))
{
var dirName = new DirectoryInfo(d).Name;
ListBox1.Items.Add(dirName);
}
I just used route of C for testing.