如何在Windows应用程序中将相对路径转换为绝对路径?
我知道我们可以在ASP.NET中使用server.MapPath().但是我们可以在Windows应用程序中做些什么呢?
我的意思是,如果有一个.NET内置函数可以处理...
Jon*_*eet 170
你有没有尝试过:
string absolute = Path.GetFullPath(relative);
Run Code Online (Sandbox Code Playgroud)
?请注意,这将使用进程的当前工作目录,而不是包含可执行文件的目录.如果这没有帮助,请澄清您的问题.
Tob*_*orn 16
如果你想获得相对于你的.exe的路径,那么使用
string absolute = Path.Combine(Application.ExecutablePath, relative);
Run Code Online (Sandbox Code Playgroud)
Nye*_*uds 13
这适用于不同驱动器上的路径,驱动器相对路径和实际相对路径.哎呀,如果它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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65462 次 |
| 最近记录: |