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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1399008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:05:06  来源:igfitidea点击:

How to convert a relative path to an absolute path in a Windows application?

c#

提问by Amit Dhall

How do I convert a relative path to an absolute path in a Windows application?

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

I know we can use server.MapPath() in ASP.NET. But what can we do in a Windows application?

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

I mean, if there is a .NET built-in function that can handle that...

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

采纳答案by Jon Skeet

Have you tried:

你有没有尝试过:

string absolute = Path.GetFullPath(relative);

? Note that that will use the current working directory of the process, not the directory containing the executable. If that doesn't help, please clarify your question.

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

回答by Tobias Hertkorn

If you want to get the path relative to your .exe then use

如果要获取相对于 .exe 的路径,请使用

string absolute = Path.Combine(Application.ExecutablePath, relative);

回答by Nyerguds

This one works for paths on different drives, for drive-relative paths and for actual relative paths. Heck, it even works if the basePathisn't actually absolute; it always uses the current working directory as final fallback.

这适用于不同驱动器上的路径、驱动器相对路径和实际相对路径。哎呀,如果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);
}

回答by vesi

It's a bit older topic, but it might be useful for someone. I have solved a similar problem, but in my case, the path was not at the beginning of the text.

这是一个有点老的话题,但它可能对某人有用。我已经解决了类似的问题,但就我而言,路径不在文本的开头。

So here is my solution:

所以这是我的解决方案:

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;
    }
}

Example:

例子:

Data Source=.\Data\Data.sdf;Persist Security Info=False;
Data Source=..\..\bin\Debug\Data\Data.sdf;Persist Security Info=False;