C# Path.Combine 绝对与相对路径字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/670566/
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-04 12:40:52  来源:igfitidea点击:

Path.Combine absolute with relative path strings

c#.netwindowspathfilesystems

提问by CVertex

I'm trying to join a Windows path with a relative path using Path.Combine.

我正在尝试使用Path.Combine.

However, Path.Combine(@"C:\blah",@"..\bling")returns C:\blah\..\blinginstead of C:\bling\.

但是,Path.Combine(@"C:\blah",@"..\bling")返回C:\blah\..\bling而不是C:\bling\

Does anyone know how to accomplish this without writing my own relative path resolver (which shouldn't be too hard)?

有谁知道如何在不编写我自己的相对路径解析器的情况下完成此操作(这应该不会太难)?

回答by shahkalpesh


Path.GetFullPath(@"c:\windows\temp\..\system32")?

回答by Llyle

What Works:

什么有效:

string relativePath = "..\bling.txt";
string baseDirectory = "C:\blah\";
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);

(result: absolutePath="C:\bling.txt")

(结果:absolutePath="C:\bling.txt")

What doesn't work

什么不起作用

string relativePath = "..\bling.txt";
Uri baseAbsoluteUri = new Uri("C:\blah\");
string absolutePath = new Uri(baseAbsoluteUri, relativePath).AbsolutePath;

(result: absolutePath="C:/blah/bling.txt")

(结果:absolutePath="C:/blah/bling.txt")

回答by Colonel Panic

Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx

在组合路径http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx上调用 Path.GetFullPath

> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling"))
C:\bling

(I agree Path.Combine ought to do this by itself)

(我同意 Path.Combine 应该自己做这件事)

回答by Jonathan Mc Namee

This will give you exactly what you need (path does NOT have to exist for this to work)

这将为您提供您所需要的(路径不一定要存在才能工作)

DirectoryInfo di = new DirectoryInfo(@"C:\blah\..\bling");
string cleanPath = di.FullName;

回答by thumbmunkeys

For windows universal apps Path.GetFullPath()is not available, you can use the System.Uriclass instead:

对于 Windows 通用应用程序Path.GetFullPath()不可用,您可以使用System.Uri该类:

 Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
 Console.WriteLine(uri.LocalPath);

回答by zaknafein

Be careful with Backslashes, don't forget them (neither use twice:)

小心反斜杠,不要忘记它们(不要使用两次:)

string relativePath = "..\bling.txt";
string baseDirectory = "C:\blah\";
//OR:
//string relativePath = "\..\bling.txt";
//string baseDirectory = "C:\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);

回答by U. Bulle

Path.GetFullPath()does not work with relative paths.

Path.GetFullPath()不适用于相对路径。

Here's the solution that works with both relative + absolute paths. It works on both Linux + Windows and it keeps the ..as expected in the beginning of the text (at rest they will be normalized). The solution still relies on Path.GetFullPathto do the fix with a small workaround.

这是适用于相对+绝对路径的解决方案。它适用于 Linux + Windows,并且..在文本的开头保留了预期的内容(在休息时它们将被规范化)。该解决方案仍然依赖于Path.GetFullPath通过一个小的解决方法来进行修复。

It's an extension method so use it like text.Canonicalize()

这是一种扩展方法,所以像这样使用它 text.Canonicalize()

/// <summary>
///     Fixes "../.." etc
/// </summary>
public static string Canonicalize(this string path)
{
    if (path.IsAbsolutePath())
        return Path.GetFullPath(path);
    var fakeRoot = Environment.CurrentDirectory; // Gives us a cross platform full path
    var combined = Path.Combine(fakeRoot, path);
    combined = Path.GetFullPath(combined);
    return combined.RelativeTo(fakeRoot);
}
private static bool IsAbsolutePath(this string path)
{
    if (path == null) throw new ArgumentNullException(nameof(path));
    return
        Path.IsPathRooted(path)
        && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
        && !Path.GetPathRoot(path).Equals(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal);
}
private static string RelativeTo(this string filespec, string folder)
{
    var pathUri = new Uri(filespec);
    // Folders must end in a slash
    if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) folder += Path.DirectorySeparatorChar;
    var folderUri = new Uri(folder);
    return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString()
        .Replace('/', Path.DirectorySeparatorChar));
}