Best / easiest / fastest way to get relative path between two files?

I am in the midst of some refactoring of some C # codes, and part of this is to repeat some links, because we are completely redoing the folder structure. I would just go into the .csproj or .sln file and change the paths.

However, some links have paths such as

"../../../../../../ThirdParty/SomeMicrosoftLibrary/bin/Debug/SomeMicrosoftLibrary.dll

And since we moved everything around, I need to find a new relative path. But I absolutely hate trying to do this (find out how many oblique and periods I need to add), since it always feels like a hit or a mean science.

Is there a simple way (utility, script, code snippet) to say "here is file A, here is file B, what is the relative path of file B relative to file A?"

+3
source share
3 answers

Create relative path

It is in Java, but easily translates to C #.

+2
source

With Ruby:

$ ruby -e "require 'pathname'; puts Pathname.new('foo/bar').relative_path_from(Pathname.new('baz/x/y/z')).to_s"
../../../../foo/bar

I'm sure Python has a similar method, although I don't need one.

+7
source

I know this is old, but I was looking for the answer to this question, so here is a method that does this, just in case, if it can help someone else in the future

/// <summary>
/// Finds the relative path of B with respect to A
/// </summary>
/// <param name="A">The path you're navigating from</param>
/// <param name="B">The path you're navigating to</param>
/// <returns></returns>
static string Get_PathB_wrt_PathA(string A, string B)
{
    string result = "";

    if (A == B)
        return result;

    var s = new char[] { '\\' };
    var subA = A.Split(s, StringSplitOptions.RemoveEmptyEntries).ToList();
    var subB = B.Split(s, StringSplitOptions.RemoveEmptyEntries).ToList();

    int L = subA.Count >= subB.Count ? subB.Count : subA.Count;
    int i = 0;

    for (i = 0; i < L; i++)
    {
        if (subA[0] == subB[0])
        {
            subA.RemoveAt(0);
            subB.RemoveAt(0);
        }
        else
            break;
    }

    for (i = 0; i <= subA.Count - 1; i++)
    {
        result += @"..\"; //this navigates to the preceding directory
    }

    for (i = 0; i < subB.Count; i++)
    {
        result += subB[i] + "\\";
    }

    result = result.Substring(0, result.Length - 1); //remove the extra backslash
    return result;
}
+2
source

Source: https://habr.com/ru/post/1705053/


All Articles