2009-11-19 8 views
24

이 작업을 수행하기 위해 .NET 메서드가 기본으로 제공되기를 기대하지만 찾을 수는 없습니다.C#에서 한 경로에서 다른 경로로 상대 경로를 얻는 방법

동일한 루트 드라이브에 있다는 것을 알고있는 두 개의 경로가 있습니다. 한 경로에서 다른 경로로 상대 경로를 가져올 수 있기를 원합니다.

string path1 = @"c:\dir1\dir2\"; 
string path2 = @"c:\dir1\dir3\file1.txt"; 
string relPath = MysteryFunctionThatShouldExist(path1, path2); 
// relPath == "..\dir3\file1.txt" 

이 기능이 있습니까? 그렇지 않으면 그것을 구현하는 가장 좋은 방법은 무엇입니까?

답변

47

Uri 작품 :

Uri path1 = new Uri(@"c:\dir1\dir2\"); 
Uri path2 = new Uri(@"c:\dir1\dir3\file1.txt"); 
Uri diff = path1.MakeRelativeUri(path2); 
string relPath = diff.OriginalString; 
+1

열린 우리당이 작업을 수행하지만 고칠 수있을만큼 간단하다, 슬래시를 전달하도록 전환됩니다. 감사! –

9

또한 PathRelativePathTo 기능을 가져 호출 할 수있다.

예컨대 :

using System.Runtime.InteropServices; 

public static class Util 
{ 
    [DllImport("shlwapi.dll", EntryPoint = "PathRelativePathTo")] 
    protected static extern bool PathRelativePathTo(StringBuilder lpszDst, 
     string from, UInt32 attrFrom, 
     string to, UInt32 attrTo); 

    public static string GetRelativePath(string from, string to) 
    { 
    StringBuilder builder = new StringBuilder(1024); 
    bool result = PathRelativePathTo(builder, from, 0, to, 0); 
    return builder.ToString(); 
    } 
} 
+0

나를 위해 작동하지만 "(VS2012, .NET3.5) 그렇지 않으면"CS1057 오류 : "PathRelativePathTo (System.Text.StringBuilder, string, uint, string, uint) '얻을"보호 된 " 정적 클래스는 보호 된 멤버를 포함 할 수 없습니다. " –

+0

단순한 경우를 위해 win32 API를 가져 오는 것은 과도한 것으로 보이지만 가능하다는 것을 알고있는 것이 좋습니다. – FacelessPanda

+0

@FacelessPanda 거의 무리가 없습니다. 라이브러리는 거의 확실하게로드되어 있으므로 오버 헤드가 없습니다. –

관련 문제