0

I want to find out if a certain folder has subfolders starting with a particular name.

For Eg.

In my C:\Test folder, I have folders like GUI, TCP, PLC, PLC_1, PLC_2... PLC_n.

I may or may not have PLC_ folders. I want to check whether those folders exist or not. And if they exist I want to extract the names of all such folders.

Avenger789
  • 402
  • 4
  • 14
  • http://stackoverflow.com/a/7286508/61470 –  May 08 '14 at 08:04
  • @BrokenHeartღ [**this edit**](http://stackoverflow.com/review/suggested-edits/4798621) is just a cosmetic fix on my [**previously accepted one**](http://stackoverflow.com/review/suggested-edits/4798388) - so.... thanks for your rejection. –  May 13 '14 at 10:22

4 Answers4

6

You can use the overload of Directory.GetDirectories

string[] plcDirs = Directory.GetDirectories(@"C:\Test", "PLC*", SearchOption.TopDirectoryOnly);
if(plcDirs.Any())
{
    // ...
}

If there are many sub-directories it is more efficient to use the deferred executed EnumerateDirectories which does not need to load all into memory before it can start processing:

var plcDirs = Directory.EnumerateDirectories(@"C:\Test", "PLC*", SearchOption.TopDirectoryOnly);

MSDN:

The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You can iterate through subfolders by:

DirectoryInfo folder = new DirectoryInfo(path);
DirectoryInfo[] subfolders = directory.GetDirectories();

foreach(DirectoryInfo subfolder in subfolders) 
{
    //TODO: add logic here for your check. e.g.
    if (subfolder.name.StartsWith(somestring)) 
    {
        //TODO:
    }
}
EnterSB
  • 984
  • 2
  • 10
  • 27
0

Using the following, you can search folder and subfolders using searchpattern. It is most reliable, as GetAll sometimes fails when appropriate permissions is not correct.

Get all files and directories in specific path fast

Community
  • 1
  • 1
Anthony Horne
  • 2,522
  • 2
  • 29
  • 51
0

If the name pattern of the subdirectories to be found is more complicated, you can use Regex:

var subdirs = Directory.GetDirectories(@"C:\Test")
                       .Where(dir => Regex.IsMatch(dir, @"PLC_\d+"));
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58