C#绝对路径拼接相对路径的实例代码
做项目时发现path.combine方法只能支持傻瓜式的目录拼接
//绝对路径
string absolutepath = @"c:\program files\internet explorer";
//相对路径
string relativepath = @"..\testpath\";
//预计拼接结果
string splicingresult = string.empty;
console.writeline(string.format("path.combine(\"{0}\",\"{1}\")=\"{2}\"", absolutepath, relativepath, path.combine(absolutepath, relativepath)));
输出结果为:
发现并没有按照想像的分辨出相对路径和绝对路径,所以只好用正则匹配了相对路径进行重新拼接,以下方法只支持绝对路径+相对路径的方式
//绝对路径
string absolutepath = @"c:\program files\internet explorer";
//相对路径
string relativepath = @"..\testpath\";
//预计拼接结果
string splicingresult = string.empty;
console.writeline(string.format("path.combine(\"{0}\",\"{1}\")=\"{2}\"", absolutepath, relativepath, path.combine(absolutepath, relativepath)));
if (!path.ispathrooted(relativepath))
{
//匹配相对路径,匹配需要向上推的目录层数
regex regex = new regex(@"^\\|([..]+)");
int backup = regex.matches(relativepath).count;
list<string> pathes = absolutepath.split("\\".tochararray()).tolist();
pathes.removerange(pathes.count - backup, backup);
//匹配文件名,匹配需要附加的目录层数
regex = new regex(@"^\\|([a-za-z0-9]+)");
matchcollection matches = regex.matches(relativepath);
foreach (match match in matches)
{
pathes.add(match.value);
}
//驱动器地址取绝对路径中的驱动器地址
pathes[0] = path.getpathroot(absolutepath);
foreach (string p in pathes)
{
splicingresult = path.combine(splicingresult, p);
}
}
console.writeline(string.format("absolute path={0}",absolutepath));
console.writeline(string.format("relative path={0}", relativepath));
console.writeline(string.format("path.combine(\"{0}\",\"{1}\")=\"{2}\"", absolutepath, relativepath, splicingresult));
console.readline();
输出结果: