.Net - 从路径中删除点

时间:2009-06-09 15:49:33

标签: .net path

如何将“c:\ foo \ .. \ bar”转换为“c:\ bar”?

10 个答案:

答案 0 :(得分:40)

string path = Path.GetFullPath("C:\\foo\\..\\bar"); // path = "C:\\bar"

More Info

答案 1 :(得分:6)

你试过吗

string path = Path.GetFullPath(@"C:\foo\..\bar");
使用System.IO.Path类在C#中

答案 2 :(得分:3)

答案 3 :(得分:2)

我相信你所寻找的是Syetem.IO.Path,因为它提供了处理有关通用路径,甚至是互联网路径的几个问题的方法。

答案 4 :(得分:2)

尝试System.IO.Path.GetFullPath(@“c:\ foo .. \ bar”)

答案 5 :(得分:1)

我想保留相对路径而不将它们转换为绝对路径,我也希望同时支持windows和linux风格的换行符(\或/) - 所以我想出了以下公式&测试申请:

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

class Script
{
    /// <summary>
    /// Simplifies path, by removed upper folder references "folder\.." will be converted
    /// </summary>
    /// <param name="path">Path to simplify</param>
    /// <returns>Related path</returns>
    static String PathSimplify(String path)
    {
        while (true)
        {
            String newPath = new Regex(@"[^\\/]+(?<!\.\.)[\\/]\.\.[\\/]").Replace(path, "" );
            if (newPath == path) break;
            path = newPath;
        }
        return path;
    }


    [STAThread]
    static public void Main(string[] args)
    {
        Debug.Assert(PathSimplify("x/x/../../xx/bbb") == "xx/bbb");
        // Not a valid path reference, don't do anything.
        Debug.Assert(PathSimplify(@"C:\X\\..\y") == @"C:\X\\..\y");
        Debug.Assert(PathSimplify(@"C:\X\..\yy") == @"C:\yy");
        Debug.Assert(PathSimplify(@"C:\X\..\y") == @"C:\y");
        Debug.Assert(PathSimplify(@"c:\somefolder\") == @"c:\somefolder\");
        Debug.Assert(PathSimplify(@"c:\somefolder\..\otherfolder") == @"c:\otherfolder");
        Debug.Assert(PathSimplify("aaa/bbb") == "aaa/bbb");
    }
}

删除额外的上层文件夹引用(如果有)

答案 6 :(得分:0)

不是直接的答案,但是我怀疑你正试图重新发明System.IO.Path.Combine()方法的问题。这应该消除了创建路径的需要,就像你要求的整体路径一样。

答案 7 :(得分:0)

如果您想自己这样做,可以使用以下代码:

var normalizePathRegex = new Regex(@"\[^\]+\..");
var path = @"C:\lorem\..\ipsum"
var result = normalizePathRegex.Replace(unnormalizedPath, x => string.Empty);

URL和UNIX风格的路径:

var normalizePathRegex = new Regex(@"/[^/]+/..");
var path = @"/lorem/../ipsum"
var result = normalizePathRegex.Replace(unnormalizedPath, x => string.Empty);

注意:在实际应用程序中使用此代码时,请务必使用RegexOptions.Compiled

答案 8 :(得分:0)

这是在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));
}

答案 9 :(得分:0)

转换为完整路径并返回相对路径

public static string MakeRelative(string filePath, string referencePath)
{
    var fileUri = new Uri(filePath);
    var referenceUri = new Uri(referencePath);
    return Uri.UnescapeDataString(referenceUri.MakeRelativeUri(fileUri).ToString()).Replace('/', Path.DirectorySeparatorChar);
}

public static string SimplifyRelativePath(string path)
{
    var fullPath = Path.GetFullPath(path);
    var result = MakeRelative(fullPath, Directory.GetCurrentDirectory() + "\\");
    return result;
}