Mo_Code Mo_Code - 1 month ago 11
C# Question

Get Child Directory from Path

How can i split the Path to get the Value CustomCompanyNames?

C:\Project\v4.0\Tool\Custom\CustomCompanyNames\Template\bin\file\file.xml


How can i get the Value?

Answer

If you want to get for a specific file the parent directory of "Template" directory you can try this:

public string GetTemplateDirectoryParentName(string filePath)
{
    FileInfo fileInfo = new FileInfo(filePath);
    DirectoryInfo directoryInfo = fileInfo.Directory;
    while(directoryInfo.Name != "Tempalte")
    {
        direcotryInfo = direcotryInfo.Parent;
    }
    return direcotryInfo.Parent.Name;
}

You can do it the other way by getting the child directory of "Custom" directory:

public string GetTemplateDirectoryParentName(string filePath)
{
    FileInfo fileInfo = new FileInfo(filePath);
    DirectoryInfo directoryInfo = fileInfo.Directory;
    while(directoryInfo.Parent.Name != "Custom")
    {
        direcotryInfo = direcotryInfo.Parent;
    }
    return direcotryInfo.Name;
}