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

时间:2009-03-22 04:50:53

标签: c# .net windows path filesystems

我正在尝试使用Path.Combine加入具有相对路径的Windows路径。

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

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

7 个答案:

答案 0 :(得分:57)

有效:

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

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

什么行不通

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

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

答案 1 :(得分:29)

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

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

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

答案 2 :(得分:15)


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

答案 3 :(得分:3)

这将为您提供您所需要的(路径不必存在以便工作)

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

答案 4 :(得分:2)

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

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

答案 5 :(得分:1)

请注意反斜杠,请不要忘记它们(不要使用两次:)

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

答案 6 :(得分:1)

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