Esta funciona de caminos en diferentes dispositivos, para rutas de unidad-relativo y para las rutas relativas reales. Diablos, incluso funciona si el basePath
no es realmente absoluto; siempre usa el directorio de trabajo actual como respaldo final.
public static String GetAbsolutePath(String relativePath, String basePath)
{
if (relativePath == null)
return null;
if (basePath == null)
basePath = Path.GetFullPath("."); // quick way of getting current working directory
else
basePath = GetAbsolutePath(basePath, null); // to be REALLY sure ;)
String path;
// specific for windows paths starting on \ - they need the drive added to them.
// I constructed this piece like this for possible Mono support.
if (!Path.IsPathRooted(relativePath) || "\\".Equals(Path.GetPathRoot(relativePath)))
{
if (relativePath.StartsWith(Path.DirectorySeparatorChar.ToString()))
path = Path.Combine(Path.GetPathRoot(basePath), relativePath.TrimStart(Path.DirectorySeparatorChar));
else
path = Path.Combine(basePath, relativePath);
}
else
path = relativePath;
// resolves any internal "..\" to get the true full path.
return Path.GetFullPath(path);
}
¿Se refiere a una ruta relativa al directorio actual, es decir, el directorio de trabajo, o en relación con la ubicación del archivo .exe? –
Hay dos tipos de rutas relativas. Uno si tiene la forma "A \ B \ C" y no implica una base particular. El otro tiene la forma ". \ A \ B" o ".. \ A \ B"; esos son relativos al directorio de trabajo actual. – MSalters
@Amit Dhall: Por cierto, es bueno aceptar y votar la (s) respuesta (s) que lo ayuden. –