Question

Given a path and a certain section, how can I find the name of the folder immediately below that section?

This is hard to explain, let me give some examples. Suppose I am looking for the name of the folder below 'Dev/Branches'. Below are example inputs, with the expected results in bold

  • C:\Code\Dev\Branches\ Latest \bin\abc.dll
  • C:\Dev\Branches\ 5.1
  • D:\My Documents\Branches\ 7.0 \Source\Tests\test.cs

I am using C#

Edit: I suppose I could use the regex /Dev/Branches/(.*?)/ capturing the first group, but is there a neater solution without regex? That regex would fail on the second case, anyway.

Was it helpful?

Solution 5

I went with this

public static string GetBranchName(string path, string prefix)
{
    string folder = Path.GetDirectoryName(path);

    // Walk up the path until it ends with Dev\Branches
    while (!String.IsNullOrEmpty(folder) && folder.Contains(prefix))
    {
        string parent = Path.GetDirectoryName(folder);
        if (parent != null && parent.EndsWith(prefix))
            return Path.GetFileName(folder);

        folder = parent;
    }

    return null;
}

OTHER TIPS

// starting path
string path = @"C:\Code\Dev\Branches\Latest\bin\abc.dll";

// search path
string search = @"Dev\Branches";

// find the index of the search criteria
int idx = path.IndexOf(search);

// determine whether to exit or not
if (idx == -1 || idx + search.Length >= path.Length) return;

// get the substring AFTER the search criteria, split it and take the first item
string found = path.Substring(idx + search.Length).Split("\\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First();

Console.WriteLine(found);

Here's the code that will do exactly what you expect:

public static string GetSubdirectoryFromPath(string path, string parentDirectory, bool ignoreCase = true)
{
    // 1. Standarize the path separators.
    string safePath = path.Replace("/", @"\");
    string safeParentDirectory = parentDirectory.Replace("/", @"\").TrimEnd('\\');

    // 2. Prepare parentDirectory to use in Regex.
    string directory = Regex.Escape(safeParentDirectory);

    // 3. Find the immediate subdirectory to parentDirectory.
    Regex match = new Regex(@"(?:|.+)" + directory + @"\\([^\\]+)(?:|.+)", ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);

    // 4. Return the match. If not found, it returns null.
    string subDirectory = match.Match(safePath).Groups[1].ToString();
    return subDirectory == "" ? null : subDirectory;
}

A test code:

void Test()
{
    string path1 = @"C:\Code\Dev\Branches\Latest\bin\abc.dll";
    string path2 = @"C:\Dev\Branches\5.1";
    string path3 = @"D:\My Documents\Branches\7.0\Source\test.cs";

    Console.WriteLine("Matches:");
    Console.WriteLine(GetSubdirectoryFromPath(path1, "dev/branches/") ?? "Not found");
    Console.WriteLine(GetSubdirectoryFromPath(path1, @"Dev\Branches") ?? "Not found");
    Console.WriteLine(GetSubdirectoryFromPath(path3, "D:/My Documents/Branches") ?? "Not found");
    // Incorrect parent directory.
    Console.WriteLine(GetSubdirectoryFromPath(path2, "My Documents") ?? "Not found");
    // Case sensitive checks.
    Console.WriteLine(GetSubdirectoryFromPath(path3, @"My Documents\Branches", false) ?? "Not found");
    Console.WriteLine(GetSubdirectoryFromPath(path3, @"my Documents\Branches", false) ?? "Not found");

    // Output:
    //
    // Matches:
    // Latest
    // Latest
    // 7.0
    // Not found
    // 7.0
    // Not found
}

Break it down into smaller steps and you can solve this yourself:

  1. (Optional, depending on further requirements): Get the directory name (file is irrelevant): Path.GetDirectoryName(string)
  2. Get its parent directory Directory.GetParent(string).

This comes down to;

 var directory = Path.GetDirectoryName(input);
 var parentDirectory = Directory.GetParent(directory);

The supplied C:\Dev\Branches\5.1 -> 5.1 does not conform to your specification, that is the directory name of the input path itself. This will output Branches.

new Regex("\\?" + PathToMatchEscaped + "\\(\w+)\\?").Match()...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top