开发者

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

开发者 https://www.devze.com 2023-01-23 05:43 出处:网络
This question already has answers here: 开发者_如何学运维 How to get relative path from absolute path
This question already has answers here: 开发者_如何学运维 How to get relative path from absolute path (24 answers) Closed 9 years ago.

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\


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("/", "\\");


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


Updated: since the constructor is now obsolete you can use:

Uri.UnescapeDataString(new Uri(file1).MakeRelativeUri(new Uri(file2)).ToString())
  .Replace("/", "\\");

old version:

Kirk Woll's idea is good but you need to ensure your path doesn't get mangled (e.g. spaces replaced by %20) by telling Uri not to escape your path:

var result = new Uri(file1, true)
    .MakeRelativeUri(new Uri(file2, true))
    .ToString()
    .Replace("/", "\\");
0

精彩评论

暂无评论...
验证码 换一张
取 消