[ACCEPTED]-Remove dots from the path in .NET-path

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

More Info

0

Score: 8

Have you tried

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

in C# using the System.IO.Path 1 class?

Score: 3
Score: 3

I wanted to preserve relative path's without 5 converting them into absolute path, also 4 I wanted to support both - windows and linux 3 style linefeeds (\ or /) - so I've came 2 up with following formula & test application:

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

Remove 1 extra upper folder references if any

Score: 2

I believe what you're looking for is Syetem.IO.Path as 3 it provides methods to deal with several 2 issues regarding generic paths, even Internet 1 paths.

Score: 2

Try System.IO.Path.GetFullPath(@"c:\foo..\bar")

0

Score: 0

In case you want to do this yourself, you 3 may use this code:

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

URLs and UNIX-style paths:

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

Note: Remember 2 to use RegexOptions.Compiled when utilizing this code in a real-world 1 application

Score: 0

Here's the solution that works with both 4 relative and absolute paths on both Linux 3 + Windows. The solution still relies on 2 Path.GetFullPath to do the fix with a small workaround.

It's 1 an extension method so use it like 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));
}
Score: 0

Convert to full path and back to a relative 1 path

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

More Related questions