Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does there exist a method in C# to get the relative path given two absolute path inputs? [duplicate]

Does there exist a method in C# to get the relative path given two absolute path inputs?

That is I would have two inputs (with the first folder as the base) such as

c:\temp1\adam\

and

c:\temp1\jamie\

Then the output would be

..\jamie\
like image 682
Matt Avatar asked Nov 01 '10 23:11

Matt


People also ask

What are methods in C?

Methods are also known as the functions of a class. They are primarily used to provide code reusability, which saves computational time and makes the code well structured and clean. Methods also increase code readability since the same set of operations do not need to be written again and again.

Do we have methods in C++?

Classes and their member functions (or methods) are integral features of the object-oriented C++ programming language. By tying these functions to an object's namespace, class methods make your C++ code modular and reusable.


2 Answers

Not sure if there is a better way, but this will work:

var file1 = @"c:\temp1\adam\";
var file2 = @"c:\temp1\jamie\";

var result = new Uri(file1)
    .MakeRelativeUri(new Uri(file2))
    .ToString()
    .Replace("/", "\\");
like image 196
Kirk Woll Avatar answered Oct 01 '22 14:10

Kirk Woll


this is simple. Steps:

  1. Remove common beginning of string (c:\temp1\)
  2. Count number of directories of first path (1 in your case)
  3. Replace them with ..
  4. Add second path
like image 42
Andrey Avatar answered Oct 01 '22 13:10

Andrey