当前位置: 动力学知识库 > 问答 > 编程问答 >

Related paths in c#

问题描述:

I have this situation in c# application

have 2 paths in my windows

C:\Projectos\FrameworkCS\CSoft.Core

C:\Projectos2\CSoft.Core

and i need get related path of second related with first like this:

..\..\Projectos2\CSoft.Core

Exists a way to do this in c# or some one have a function can help me

网友答案:

Try MakeRelativeUri:

Uri first = new Uri(@"C:\Projectos2\CSoft.Core");
Uri second = new Uri(@"C:\Projectos\FrameworkCS\CSoft.Core ");

string relativePath = second.MakeRelativeUri(first).ToString();

Result:

"../../Projectos2/CSoft.Core"
网友答案:

I would probably figure it out by splitting both using the '\' as a separator. I would then count array items that were the same to get my common bond. Then I would build the destination path using the remaining items in the destination array and build the ..\ string by counting the remaining items in the source.

  • Common path = C:\Projectos\
  • Remaining destination path = CSoft.Core
  • Remaining source path has 1 more item (not including the file name itself) giving you ..\

Join the ..\ with the CSoft.Core giving you ..\CSoft.Core

Addendum: I didn't realise you could use the URI.MakeRelativePath() method for this - don't bother reinventing the wheel if it's already been done elsewhere.

分享给朋友:
您可能感兴趣的文章:
随机阅读: