将绝对值与相对路径字符串组合在一起

我正在尝试使用 Path.Combine将 Windows 路径与相对路径连接起来。

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

有没有人知道如何在不编写自己的相对路径解析器的情况下完成这个任务(这应该不会太难) ?

127208 次浏览

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

什么有效:

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

(result: AbsolutePath = “ C: bling.txt”)

什么行不通

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

(result: AbsolutePath = “ C:/bling.txt”)

在组合路径 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)

这将给你正是你需要的(路径不必存在,为此工作)

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

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

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

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

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

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

下面是同时使用相对路径和绝对路径的解决方案。它在 Linux + Windows 上都可以工作,并且在文本的开头保持 ..(在其他地方它们将被标准化)。该解决方案仍然依赖于 Path.GetFullPath用一个小的变通方法来完成修复。

它是一种扩展方法,所以像使用 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));
}