Get folder names in C#

| August 11, 2010 | 0 Comments

Sometimes we need to know all folders in our particular directory. But generally the code used for retrieving folders in directory return folder names with full path. For e.g. my directory X: is having two folders named Folder1 and Folder2. So if I use code I would get something like X:\Folder1, X:\Folder2. 

But  I do not need folder with full path, I just want to get folder names ONLY. So check out the code where each region includes the different way of getting only folders in that directory.

Code Snippet

I have used three controls on Form as TextBox named txtLocation (for getting path to that directory), Button named btnRetrieve (to execute code) & ComboBox named comboBox1.  Rest check the code. You would need to make comments any of two regions so that code can work fine.


private void btnRetrieve_Click(object sender, EventArgs e)
    string location = txtLocation.Text;
#region First
string[] fullName = Directory.GetDirectories(location);
foreach (string s in fullName)
string[] folder = s.Split(Path.DirectorySeparatorChar);
comboBox1.Items.Add(folder[folder.LongLength - folder.Rank].ToString());

#region Second
DirectoryInfo di = new DirectoryInfo(location);
DirectoryInfo[] sd = di.GetDirectories();
foreach (DirectoryInfo info in sd)

#region Third
string[] directories = Directory.GetDirectories(location);
foreach (string s in directories)

if (comboBox1.Items.Count > 0)
comboBox1.SelectedIndex = 0;

Category: .NET

Leave a Reply

%d bloggers like this: