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();
输出结果:
您可能感兴趣的文章:
- [代码实例][Linux系统编程]判断相对路径或绝对路径
- asp.net(C#)服务器绝对路径转换成URL相对路径[修改]
- asp.net实现上传文件显示本地绝对路径的实例代码
- asp中将相对路径转换为绝对路径的函数代码
- C#如何把html中的相对路径变成绝对路径
- 创建File实例的相对路径与绝对路径
- C# ,asp.net 获取当前,相对,绝对路径
- asp.net实现上传文件显示本地绝对路径的实例代码
- C#中相对路径转换为绝对路径的方法
- c# winform 绝对路径与相对路径
- Bottle实例—重定向函数redirect返回静态文本和相对路径与绝对路径( Absolute and Relative Paths)问题
- asp.net(C#)服务器绝对路径与URL相对路径互转
- linux C++ 获取文件绝对路径的实例代码
- 常见的跳转、相对绝对路径、在重定向代码之后写输出语句会不会执行?
- C#加载图片时,对同一图片,绝对路径没问题,相对路径报错。
- C# ,asp.net 获取当前,相对,绝对路径
- File构建实例的路径:绝对路径和相对路径
- C# 将绝对路径转换为相对路径
- asp.net项目中根据给出的相对地址获取网站绝对地址的C#代码
- c#中绝对路径和相对路径