2012-01-30 99 views
18

我有2個文件:計算相對文件路徑

C:\Program Files\MyApp\images\image.png 

C:\Users\Steve\media.jpg 

現在我想計算文件2(media.jpg)相關的文件,文件路徑1:

..\..\..\Users\Steve\ 

是否有一個在.NET中內置函數來做到這一點?

回答

21

用途:

var s1 = @"C:\Users\Steve\media.jpg"; 
var s2 = @"C:\Program Files\MyApp\images\image.png"; 

var uri = new Uri(s2); 

var result = uri.MakeRelativeUri(new Uri(s1)).ToString(); 
+1

應該指出的是,使用這種方法的時候了相對路徑將被賦予'/'而不是'\'。輸出結果如下:../../..Users/Steve/一個簡單的替換會糾正這個文件路徑。 – 2012-12-18 13:35:30

+0

這不處理所有邊緣情況。請參閱[this](http://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path/32113484#32113484)回答。 – 2015-08-20 10:41:35

4

沒有內置.NET,但有本地功能。使用這樣的:

[DllImport("shlwapi.dll", CharSet=CharSet.Auto)] 
static extern bool PathRelativePathTo(
    [Out] StringBuilder pszPath, 
    [In] string pszFrom, 
    [In] FileAttributes dwAttrFrom, 
    [In] string pszTo, 
    [In] FileAttributes dwAttrTo 
); 

或者,如果你還是喜歡託管代碼,然後試試這個:

public static string GetRelativePath(FileSystemInfo path1, FileSystemInfo path2) 
    { 
     if (path1 == null) throw new ArgumentNullException("path1"); 
     if (path2 == null) throw new ArgumentNullException("path2"); 

     Func<FileSystemInfo, string> getFullName = delegate(FileSystemInfo path) 
     { 
      string fullName = path.FullName; 

      if (path is DirectoryInfo) 
      { 
       if (fullName[fullName.Length - 1] != System.IO.Path.DirectorySeparatorChar) 
       { 
        fullName += System.IO.Path.DirectorySeparatorChar; 
       } 
      } 
      return fullName; 
     }; 

     string path1FullName = getFullName(path1); 
     string path2FullName = getFullName(path2); 

     Uri uri1 = new Uri(path1FullName); 
     Uri uri2 = new Uri(path2FullName); 
     Uri relativeUri = uri1.MakeRelativeUri(uri2); 

     return relativeUri.OriginalString; 
    }