如何在Windows应用程序中将相对路径转换为绝对路径?
我知道在ASP.NET中可以使用server.MapPath()。但是在Windows应用程序中我们该怎么办呢?
我的意思是,如果有一个.NET内置函数可以处理这个问题的话...
如何在Windows应用程序中将相对路径转换为绝对路径?
我知道在ASP.NET中可以使用server.MapPath()。但是在Windows应用程序中我们该怎么办呢?
我的意思是,如果有一个.NET内置函数可以处理这个问题的话...
你尝试过:
string absolute = Path.GetFullPath(relative);
请注意,这将使用进程的当前工作目录,而不是包含可执行文件的目录。如果这并没有帮助到您,请澄清您的问题。
如果您想获取相对于您的 .exe 文件的路径,则使用以下方法
string absolute = Path.Combine(Application.ExecutablePath, relative);
Path.Combine
甚至不能处理驱动器相对路径。它似乎忽略了初始路径。我将发布我的完整解决方案。 - Nyerguds..
的任何字符开头,它将产生垃圾数据。 - Jonathan Wood..
的路径。如果这让你感到困扰,可以执行 absolute = Path.GetFullPath(absolute)
来解决它。 - Nyerguds这个方法适用于不同驱动器的路径,驱动器相对路径和实际相对路径。甚至,如果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
相比是反向的。虽然很容易修复,但我避免这样做,因为我经常使用它来解析工作目录上的相对路径,并且将 null 作为第一个参数看起来很奇怪。 - Nyerguds这是一个有些老的话题,但对某些人可能会有用处。 我解决了一个类似的问题,但在我的情况下,路径不在文本开头。
所以这是我的解决方案:
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
会自动解析.\和..\。此外,你正在一般性地向String类添加AbsolutePath
扩展函数...可能有点过度设计了。 - NyergudsWindows 10 Python 3.8:类型对象“Path”没有属性“GetFullPath”