2009-11-19 5 views
24

J'espère qu'il existe une méthode .NET intégrée pour cela, mais je ne le trouve pas.Comment obtenir un chemin relatif d'un chemin à un autre en C#

J'ai deux chemins que je sais être sur le même lecteur racine, je veux être en mesure d'obtenir un chemin relatif de l'un à l'autre.

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

Cette fonction existe-t-elle? Sinon, quelle serait la meilleure façon de le mettre en œuvre?

Répondre

47

Uri œuvres:

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

Uri fonctionne, mais passe en slashes, ce qui est assez facile à corriger. Merci! –

9

Vous pouvez également importer la fonction PathRelativePathTo et l'appeler.

.: par exemple

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

Fonctionne pour moi, mais j'ai dû supprimer le "protégé", sinon (avec VS2012, .NET3.5) je reçois l'erreur CS1057: "PathRelativePathTo (System.Text.StringBuilder, chaîne, uint, chaîne, uint)": les classes statiques ne peuvent pas contenir de membres protégés " –

+0

L'importation de l'API win32 pour un cas simple comme celui-ci semble en faire trop, bien qu'il soit bon de savoir que c'est possible. – FacelessPanda

+0

@FacelessPanda Il n'en coûte presque rien - la bibliothèque est presque certainement chargée, son utilisation n'a donc aucune surcharge. –

Questions connexes