2009-11-19 7 views
24

? Espero que haya un método .NET incorporado para hacer esto, pero no lo estoy encontrando.¿Cómo obtengo una ruta relativa de una ruta a otra en C#

Tengo dos rutas que sé que están en la misma unidad raíz, quiero poder obtener una ruta relativa de una a la otra.

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

¿Esta función existe? Si no, ¿cuál sería la mejor manera de implementarlo?

Respuesta

47

Uri obras:

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 hace el trabajo, pero cambiará a barras inclinadas, que es bastante fácil de solucionar. ¡Gracias! –

9

También podrían importar la función PathRelativePathTo y llamarlo.

ej .:

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

Funciona para mí, pero tuve que eliminar el "protegido", de lo contrario (con VS2012, .NET3.5) aparece el error CS1057: "PathRelativePathTo (System.Text.StringBuilder, string, uint, string, uint) ': las clases estáticas no pueden contener miembros protegidos " –

+0

La importación de la API de win32 para un caso simple como ese parece exagerar, aunque es bueno saber que es posible. – FacelessPanda

+0

@FacelessPanda No es exagerado: la biblioteca está casi cargada de todas formas, por lo que su uso no tiene gastos generales. –

Cuestiones relacionadas