ChrisJJ
ChrisJJ

Reputation: 2292

How to find filepath relative from one absolute to another?

e.g. myfunc(from:c:\my\dir,to:c:\my\other\file.ext) ==> ..\other\file.ext .

new Uri() need not apply, unless there's a remedy for it returning URI format not Windows filename format. .LocalPath fails.

Upvotes: 1

Views: 56

Answers (1)

Daniel N
Daniel N

Reputation: 417

This should do what you want.

        string firstDirectory = "c:\\my\\dir";
        string secondDirectory = "c:\\my\\other\\file.ext";


        var first = firstDirectory.Split('\\');
        var second = secondDirectory.Split('\\');

        var directoriesToGoBack = first.Except(second);
        var directoriesToGoForward = second.Except(first);

        StringBuilder directory = new StringBuilder();

        bool initial = true;
        foreach (string s in directoriesToGoBack)
        {
            if (initial)
            {
                initial = false;
            } else
            {
                directory.Append('\\');
            }
            directory.Append("..");

        }

        foreach (string s in directoriesToGoForward)
        {
            directory.Append('\\');
            directory.Append(s);
        }
        Console.WriteLine(directory.ToString());

Upvotes: 1

Related Questions