Compare paths from the end in C#

Today at work, a colleague came to me with quite interesting problem. He needed to find out first common directory for two given paths starting from the end.

For example, for given paths like:

c:\documents and settings\some user\my files\projects\project1\initialFiles\somefiles\ and

d:\ My Projects\project1\ChangedFiles\MyFiles\

It would return ‘project1‘.

I was surprised to find out that neither System.IO.Path, nor System.IO.Directory allows you to that. Here’s simple solution I created for him.

public static string FindLastCommonParentFolder(string path1, string path2)

{

    if (string.IsNullOrEmpty(path1))

        throw new ArgumentException();

    if (string.IsNullOrEmpty(path2))

        throw new ArgumentException();

    try

    {

        //ensures that paths are valid

        path1 = Path.GetFullPath(path1);

        path2 = Path.GetFullPath(path2);

    }

    catch (PathTooLongException ex)

    { /*handle exception}*/}

    catch (ArgumentException ex)

    { /*handle exception}*/}

    catch (NotSupportedException ex)

    { /*handle exception}*/}

    catch (SecurityException ex)

    { /*handle exception}*/}

 

    if (path1 == path2)

        return path1.Substring(path1.LastIndexOf(Path.DirectorySeparatorChar));

 

    string[] folders1 = path1.Split(Path.DirectorySeparatorChar);

    string[] folders2 = path2.Split(Path.DirectorySeparatorChar);

    if (folders1.Length < 1 || folders2.Length < 1) 

        return string.Empty;

 

    for (int i = folders1.Length - 1; i >= 0; i--)

    {

        for (int j = folders2.Length - 1; j >= 0; j--)

        { 

            if(folders1[i]==folders2[j])

                return folders1[i];

        }

    }

    return string.Empty;

}

Comments

praaaaaaaaaaaaaaaaaaaa says:

nice code but i want demo so i will use