¿Cómo convierto una ruta relativa en una ruta absoluta en una aplicación de Windows?
Sé que podemos usar server.MapPath () en ASP.NET. Pero, ¿qué podemos hacer en una aplicación de Windows?
Quiero decir, si hay una función incorporada de .NET que puede manejar eso ...
Respuestas:
Has probado:
string absolute = Path.GetFullPath(relative);
? Tenga en cuenta que utilizará el directorio de trabajo actual del proceso, no el directorio que contiene el ejecutable. Si eso no ayuda, aclare su pregunta.
fuente
Si desea obtener la ruta relativa a su .exe, use
string absolute = Path.Combine(Application.ExecutablePath, relative);
fuente
Path.Combine
que ni siquiera puede manejar rutas relativas a la unidad. Simplemente ignora la ruta inicial que parece. Estoy publicando mi propia solución completa...
, producirá basura...
) es perfectamente aceptada y resuelta por todos los sistemas de manipulación de archivos en .Net. Si le molesta, ejecúteloabsolute = Path.GetFullPath(absolute)
.Este funciona para rutas en diferentes unidades, para rutas relativas a unidades y para rutas relativas reales. Diablos, incluso funciona si
basePath
no es realmente absoluto; siempre usa el directorio de trabajo actual como respaldo final.public static String GetAbsolutePath(String path) { return GetAbsolutePath(null, path); } public static String GetAbsolutePath(String basePath, String path) { if (path == null) return null; if (basePath == null) basePath = Path.GetFullPath("."); // quick way of getting current working directory else basePath = GetAbsolutePath(null, basePath); // to be REALLY sure ;) String finalPath; // 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(path) || "\\".Equals(Path.GetPathRoot(path))) { if (path.StartsWith(Path.DirectorySeparatorChar.ToString())) finalPath = Path.Combine(Path.GetPathRoot(basePath), path.TrimStart(Path.DirectorySeparatorChar)); else finalPath = Path.Combine(basePath, path); } else finalPath = path; // resolves any internal "..\" to get the true full path. return Path.GetFullPath(finalPath); }
fuente
Path.Combine
. Eso se soluciona fácilmente, pero lo evito ya que a menudo lo uso para resolver rutas relativas en el directorio de trabajo, y dar un valor nulo como primer argumento parece extraño.Es un tema un poco más antiguo, pero podría ser útil para alguien. He resuelto un problema similar, pero en mi caso, la ruta no estaba al principio del texto.
Entonces aquí está mi solución:
public static class StringExtension { private const string parentSymbol = "..\\"; private const string absoluteSymbol = ".\\"; public static String AbsolutePath(this string relativePath) { string replacePath = AppDomain.CurrentDomain.BaseDirectory; int parentStart = relativePath.IndexOf(parentSymbol); int absoluteStart = relativePath.IndexOf(absoluteSymbol); if (parentStart >= 0) { int parentLength = 0; while (relativePath.Substring(parentStart + parentLength).Contains(parentSymbol)) { replacePath = new DirectoryInfo(replacePath).Parent.FullName; parentLength = parentLength + parentSymbol.Length; }; relativePath = relativePath.Replace(relativePath.Substring(parentStart, parentLength), string.Format("{0}\\", replacePath)); } else if (absoluteStart >= 0) { relativePath = relativePath.Replace(".\\", replacePath); } return relativePath; } }
Ejemplo:
fuente
Path.GetFullPath
resuelve. \ y .. \ automáticamente. Además, está agregando laAbsolutePath
función de extensión a la clase String en general ... puede ser un poco exagerado.