-
C#教程之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();
输出结果: