alex2k8
alex2k8

Reputation: 43214

Remove dots from the path in .NET

How can I convert c:\foo\\..\bar into c:\bar?

Upvotes: 33

Views: 10238

Answers (10)

chtenb
chtenb

Reputation: 16194

Convert to full path and back to a relative 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;
}

Upvotes: 0

U. Bulle
U. Bulle

Reputation: 1105

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

It's 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));
}

Upvotes: 1

TarmoPikaro
TarmoPikaro

Reputation: 5243

I wanted to preserve relative path's without converting them into absolute path, also I wanted to support both - windows and linux style linefeeds (\ or /) - so I've came 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 extra upper folder references if any

Upvotes: 3

user3638471
user3638471

Reputation:

In case you want to do this yourself, you 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 to use RegexOptions.Compiled when utilizing this code in a real-world application

Upvotes: 0

RichardOD
RichardOD

Reputation: 29157

Use Path.GetFullPath

Upvotes: 4

Colin Desmond
Colin Desmond

Reputation: 4854

Have you tried

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

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

Upvotes: 8

Vasu Balakrishnan
Vasu Balakrishnan

Reputation: 1771

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

Upvotes: 2

Wyatt Barnett
Wyatt Barnett

Reputation: 15663

Not a direct answer, but from the question I suspect you are trying to reinvent the System.IO.Path.Combine() method. That should eliminate the need to create paths like the one you are asking about overall.

Upvotes: -1

Paulo Santos
Paulo Santos

Reputation: 11587

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

Upvotes: 2

Randolpho
Randolpho

Reputation: 56439

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

More Info

Upvotes: 55

Related Questions