2012-01-30 14 views
18

ho 2 file:Calcolare relativa Filepath

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

C:\Users\Steve\media.jpg 

Ora voglio calcolare il file-percorso del file 2 (media.jpg) relativo al file 1:

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

C'è un funzione integrata in .NET per fare questo?

risposta

21

Usa:

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

Va sottolineato che quando si utilizza questo metodo che il il percorso relativo che verrà dato avrà '/' invece di '\'. L'output darebbe: ../../..Users/Steve/ Una semplice sostituzione correggerà questo per il percorso dei file. –

+0

Questo non gestisce tutti i casi limite. Vedi [this] (http://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path/32113484#32113484) risposta. –

4

Non esiste un .NET integrato, ma esiste una funzione nativa. Utilizzare in questo modo:

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

Se si continua a preferire il codice gestito quindi provare questo:

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; 
    }