2012-01-30 23 views
18

tôi có 2 Files:Tính tương đối filepath

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

C:\Users\Steve\media.jpg 

Bây giờ tôi muốn để tính toán File-Path của File 2 (media.jpg) liên quan đến File 1:

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

Có một được xây dựng trong chức năng trong. NET để làm điều này?

Trả lời

21

Sử dụng:

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

Cần chỉ ra rằng khi sử dụng phương pháp này mà đường dẫn tương đối sẽ được cung cấp sẽ có '/' thay vì '\'. Đầu ra sẽ cung cấp cho: ../../..Users/Steve/ Một thay thế đơn giản sẽ sửa lỗi này cho đường dẫn tệp. –

+0

Điều này không xử lý tất cả các trường hợp cạnh. Xem [this] (http://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path/32113484#32113484) câu trả lời. –

4

Không có sẵn .NET nhưng có chức năng gốc. Sử dụng nó như thế này:

[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 
); 

Hoặc nếu bạn vẫn thích mã số quản lý sau đó thử này:

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; 
    } 
Các vấn đề liên quan