Search code examples
c#directoryio

Get child DirectoryInfo directory of parent DirectoryInfo


I have following path:

G:\C#\Dump.WebApi\src\Dump.WebApi

string currentDirectory = GetCurrentDirectory();
DirectoryInfo directoryInfo = GetParent(currentDirectory)!.Parent!;

The result of this code is: G:\C#\Dump.WebApi

Now i want to go to bin folder. But i cant find according method.

G:\C#\Dump.WebApi\bin

What I only can its get list of subdirectories:

directoryInfo.GetDirectories();

What can I only do is:

directoryInfo.GetDirectories().Single(directoryInfo => directoryInfo.Name == "bin");

Is there simple method for this? Am I missing something obvious?

Thanks!


Solution

  • If you are seeking a concise approach, you can do this:

    directoryInfo.CreateSubdirectory("bin");
    

    Even if the bin directory already exists, this method will not have error. Of course, there will be some overhead as it will attempt to create a new directory. A more efficient approach is still to use Path.Combine:

    new DirectoryInfo(Path.Combine(directoryInfo.FullName, "bin"));