如何在Windows应用程序中将相对路径转换为绝对路径?
我知道我们可以在ASP.NET中使用server.MapPath()。但是我们可以在Windows应用程序中做什么?
我的意思是,如果有一个.NET内置函数可以处理该问题...
如何在Windows应用程序中将相对路径转换为绝对路径?
我知道我们可以在ASP.NET中使用server.MapPath()。但是我们可以在Windows应用程序中做什么?
我的意思是,如果有一个.NET内置函数可以处理该问题...
Answers:
你有没有尝试过:
string absolute = Path.GetFullPath(relative);
?请注意,这将使用进程的当前工作目录,而不是包含可执行文件的目录。如果那没有帮助,请澄清您的问题。
如果要获取相对于.exe的路径,请使用
string absolute = Path.Combine(Application.ExecutablePath, relative);
Path.Combine甚至无法处理驱动器相对路径。它只是忽略了看起来的初始路径。我正在发布自己的完整解决方案。
..,则会产生垃圾。
...Net中的所有文件处理系统都完全接受并解决了“垃圾”(包括其中的路径)问题。如果它困扰您,请执行absolute = Path.GetFullPath(absolute)它。
这适用于不同驱动器上的路径,驱动器相对路径和实际相对路径。哎呀,如果basePath实际上不是绝对的,它甚至可以工作。它始终使用当前工作目录作为最终后备。
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);
}
Path.Combine。这很容易解决,但是我避免使用它,因为我经常使用它来解析工作目录上的相对路径,并且由于第一个arg看起来很奇怪而给了null。
这是一个较旧的主题,但对某人可能有用。我已经解决了类似的问题,但就我而言,该路径不是文本的开头。
所以这是我的解决方案:
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;
}
}
例:
Data Source=.\Data\Data.sdf;Persist Security Info=False;
Data Source=..\..\bin\Debug\Data\Data.sdf;Persist Security Info=False;
Path.GetFullPath自动解析。\和.. \。另外,您AbsolutePath通常在将扩展函数添加到String类中……可能有点过大。