Home > Mobile >  How to get the names of a subfolder in c#
How to get the names of a subfolder in c#

Time:06-23

I have a folder path with me something like "c:/videos". it contains subfolders like car, bike, bus ... etc. need to get only the sub folder name and store in a string array.

And please note i don't need a full sub folder path

out needed like:- car, bike, bus

not like c:/videos/car c:/videos/bike c:/videos/bus

CodePudding user response:

You can use GetDirectories method

var directories = Directory.GetDirectories(@"c:/videos");

this will give you a string array of all the subdirectories and then you can call Path.GetDirectoryName() to get the folder name

 List<string> subfolders = List<string>();
 var directories = Directory.GetDirectories(@"c:/videos");
 foreach(var directory in directories)
 {
    subfolders.Add(Path.GetDirectoryName(directory));
 }

 var result = subfolders.ToArray();

CodePudding user response:

You have to iterate over the SubDirectories.
And replace the startpath c:\videoswith an empty string:

var rootDir = @"c:\videos";
DirectoryInfo directoryInfo = new DirectoryInfo(rootDir);

var dirs = new System.Collections.Generic.List<string>();
foreach (var dir in directoryInfo.GetDirectories())
{
    dirs.Add(dir.Name.Replace($"{rootDir}\\", ""));
}
var result = dirs.ToArray();

enter image description here

CodePudding user response:

string yourPath= @"C:\videos";

// Get all subdirectories

string[] subDirs = Directory.GetDirectories(root); 

foreach (string subdirectory in subdirectoryEntries)

    LoadSubDirs(subdirectory);


List<string> subfolders = List<string>();
private void LoadSubDirs(string dir)
{
  subfolders.Add(Path.GetDirectoryName(dir));  

  string[] subdirectoryEntries = Directory.GetDirectories(dir);

  foreach (string subdirectory in subdirectoryEntries)

  {

    LoadSubDirs(subdirectory);

  }

}
  • Related