如何在Windows应用程序中将相对路径转换为绝对路径?

Ami*_*all 81 c#

如何在Windows应用程序中将相对路径转换为绝对路径?

我知道我们可以在ASP.NET中使用server.MapPath().但是我们可以在Windows应用程序中做些什么呢?

我的意思是,如果有一个.NET内置函数可以处理...

Jon*_*eet 170

你有没有尝试过:

string absolute = Path.GetFullPath(relative);
Run Code Online (Sandbox Code Playgroud)

?请注意,这将使用进程的当前工作目录,而不是包含可执行文件的目录.如果这没有帮助,请澄清您的问题.

  • 这不取决于你从哪里开始应用程序,而不是取决于exe所在的位置?当然,这个问题并不是很清楚. (2认同)

Tob*_*orn 16

如果你想获得相对于你的.exe的路径,那么使用

string absolute = Path.Combine(Application.ExecutablePath, relative);
Run Code Online (Sandbox Code Playgroud)

  • 小心Path.Combine.如果"相对"部分以斜线开头,则可能无法按照您的想法进行操作. (3认同)
  • @silky:好吧,那不是相对的,是吗? (2认同)
  • 这无法处理相对路径。它仅接受目录和文件名。如果第二个参数以“ ..”开头,则会产生垃圾。 (2认同)

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)

  • 是的,这很明智。不能为了处理一些参数而费心编辑它。 (2认同)