正则表达式收缩Path.Combine相对于绝对

时间:2013-11-28 20:44:16

标签: c# .net regex

我有2个文件路径:

绝对的:

/Content/assets2/otherfolder/another/this/

相对

../../../../assets/img/logo.gif

当我做Path.Combine(绝对,相对)时,我得到:

/Content/assets2/otherfolder/another/this/../../../../assets/img/logo.gif

工作正常,但我想得到的是:

/Content/assets/img/logo.gif

我需要一个正则表达式或代码,用相应的文件夹删除“../”:

/Content/assets2/otherfolder/another/this/../../../../assets/img/logo.gif
/Content/assets2/otherfolder/another/../../../assets/img/logo.gif
/Content/assets2/otherfolder/../../assets/img/logo.gif
/Content/assets2/../assets/img/logo.gif
终于进入了:

/Content/assets/img/logo.gif

1 个答案:

答案 0 :(得分:7)

你不需要正则表达式。实际上,我认为在Regex中以可靠的方式定义是不可能的。而是使用Path.GetFullPath:

string combined = Path.Combine(path1, path2);
string prettyPath = Path.GetFullPath(combined);