2010-06-29 27 views

Respuesta

11

Si nos fijamos en la clase Path hay un par de métodos que debería ayudar:

Path.Combine 

y

Path.GetFullPath 

Así:

string newPath = Path.Combine(basepath, relative); 
string absolute = Path.GetFullPath(newPath); 

Aunque la segunda ISN paso estrictamente necesario: le daría un camino "más limpio" si imprimiera, por ejemplo.

+0

Nice! 'Path.GetFullPath (Path.Combine (basepath, relative))' devuelve lo que necesito. –

0

Debido Path.Combine no funciona en todos los casos que aquí hay una función más compleja :-)

static string GetFullPath(string maybeRelativePath, string baseDirectory) { 
    if (baseDirectory == null) baseDirectory = Environment.CurrentDirectory; 
    var root = Path.GetPathRoot(maybeRelativePath); 
    if (string.IsNullOrEmpty(root)) 
     return Path.GetFullPath(Path.Combine(baseDirectory, maybeRelativePath)); 
    if (root == "\\") 
     return Path.GetFullPath(Path.Combine(Path.GetPathRoot(baseDirectory), maybeRelativePath.Remove(0, 1))); 
    return maybeRelativePath; 
} 

Path.Combine(@"C:\foo\",@"\foo\bar") vuelve @"\foo\bar" y no como se esperaba @"C:\foo\bar"

+1

"... devuelve \ foo \ bar y no como C: \ foo \ bar esperado" - No sé por qué esperas eso, ya que la documentación establece explícitamente que "Si path2 contiene una ruta absoluta, este método devuelve path2 " – Joe

+0

\ foo \ bar no es absoluta en Windows falta la letra de unidad a ser absoluta - C: \ foo \ bar es ^^ – kux

+0

Con "espera" que quería decir "esperaba por el método mágico" ^^ – kux

Cuestiones relacionadas