2012-01-30 102 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; 
    }