Removing ../ in the middle of a relative path

I want to get from this

"../lib/../data/myFile.xml"

to that

"../data/myFile.xml"

I think I could do this by manipulating the string, looking for "../"and canceling them with previous folders, but I was looking for an already existing C # solution.

I tried to create an instance Urifrom this line and return to the String () command. Did not help. It leaves the string unchanged.

+4
source share
3 answers

It looks like you might need to parse / rebuild the path yourself, or use some kind of well-built regex to do this for you.

By taking the parse / rebuild route, you can do something like :

public static string NormalisePath(string path)
{
    var components = path.Split(new Char[] {'/'});

    var retval = new Stack<string>();
    foreach (var bit in components)
    {
        if (bit == "..")
        {
            if (retval.Any())
            {
                var popped = retval.Pop();
                if (popped == "..")
                {
                    retval.Push(popped);
                    retval.Push(bit);
                }
            }
            else
            {
                retval.Push(bit);
            }
        }
        else
        {
            retval.Push(bit);
        }
    }

    var final = retval.ToList();
    final.Reverse();
    return string.Join("/", final.ToArray());
}

(and yes, you probably would like to have better variable names / annotations, etc.)

+2

:

Path.GetFullPath("../lib/../data/myFile.xml")

, , , , . :

Path.GetFullPath("/lib/../data/myFile.xml")   // C:\data\myFile.xml
Path.GetFullPath("../lib/../data/myFile.xml") // C:\Program Files (x86)\data\myFile.xml
0

You can use the regular expression for this:

public static string NormalisePath(string path)
{
    return new Regex(@"\.{2}/.*/(?=\.\.)").Replace(path, "");            
}
0
source

Source: https://habr.com/ru/post/1533564/


All Articles