Reputation: 3486
Let's say I have the following relative path as a string:
"foo/./my/../bar/file.txt"
Is there a quick way to resolve the dots (like ".." and also ".") so that the result is:
"foo/bar/file.txt"
I cannot use Uri
as it is not an absolute path and I also cannot use Path.GetFullPath
because this will add the path of the executing application so that I end up with:
"C:\myAppPath\foo\bar\file.txt"
(Also it changes "/" -> "\", but I don't particularly mind this)
Upvotes: 2
Views: 2555
Reputation: 3085
You could always do something like this. Does this do the trick?
string test = "foo/./my/../bar/file.txt";
bool temp = false;
string result = "";
foreach (var str in test.Split('/'))
{
if (str.Contains(".") & str.Count(f => f=='.') == str.Length)
{
if (temp == false)
temp = true;
else
temp = false;
}
else
{
if (!temp)
{
result += str + "/";
}
}
}
result = result.Substring(0, result.Length - 1);//is there a better way to do this?
//foo/bar/file.txt
Upvotes: 1
Reputation: 223352
Just a hack,
string path = @"foo/./my/../bar/file.txt";
string newPath = Path.GetFullPath(path).Replace(Environment.CurrentDirectory, "");
You can use Path.GetFullPath
, which returns path along with Environment.CurrentDirectory
, use String.Replace
to remove current directory from the resolved path.
and you will end up with newPath = \foo\bar\file.txt
Upvotes: 7