Search code examples
c#.net-2.0

Remove part of the full directory name?


I have a list of filename with full path which I need to remove the filename and part of the file path considering a filter list I have.

Path.GetDirectoryName(file)

Does part of the job but I was wondering if there is a simple way to filter the paths using .Net 2.0 to remove part of it.

For example:

if I have the path + filename equal toC:\my documents\my folder\my other folder\filename.exe and all I need is what is above my folder\ means I need to extract only my other folder from it.

UPDATE:

The filter list is a text box with folder names separated by a , so I just have partial names on it like the above example the filter here would be my folder

Current Solution based on Rob's code:

string relativeFolder = null;
string file = @"C:\foo\bar\magic\bar.txt";
string folder = Path.GetDirectoryName(file);
string[] paths = folder.Split(Path.DirectorySeparatorChar);
string[] filterArray = iFilter.Text.Split(',');

foreach (string filter in filterArray)
{
    int startAfter = Array.IndexOf(paths, filter) + 1;
    if (startAfter > 0)
    {
        relativeFolder = string.Join(Path.DirectorySeparatorChar.ToString(), paths, startAfter, paths.Length - startAfter);
        break;
    }
}

Solution

  • How about something like this:

    private static string GetRightPartOfPath(string path, string startAfterPart)
    {
        // use the correct seperator for the environment
        var pathParts = path.Split(Path.DirectorySeparatorChar);
    
        // this assumes a case sensitive check. If you don't want this, you may want to loop through the pathParts looking
        // for your "startAfterPath" with a StringComparison.OrdinalIgnoreCase check instead
        int startAfter = Array.IndexOf(pathParts, startAfterPart);
    
        if (startAfter == -1)
        {
            // path not found
            return null;
        }
    
        // try and work out if last part was a directory - if not, drop the last part as we don't want the filename
        var lastPartWasDirectory = pathParts[pathParts.Length - 1].EndsWith(Path.DirectorySeparatorChar.ToString());
        return string.Join(
            Path.DirectorySeparatorChar.ToString(), 
            pathParts, startAfter,
            pathParts.Length - startAfter - (lastPartWasDirectory?0:1));
    }
    

    This method attempts to work out if the last part is a filename and drops it if it is.

    Calling it with

    GetRightPartOfPath(@"C:\my documents\my folder\my other folder\filename.exe", "my folder");
    

    returns

    my folder\my other folder

    Calling it with

    GetRightPartOfPath(@"C:\my documents\my folder\my other folder\", "my folder");
    

    returns the same.